Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
I think the best solution is RegEx [specifically preg_replace() or preg_match()], but to provide a solution would require the "specs" for the article references. You gave one example where the reference was three digits + period + the letter 'f'. Do they always start with a series of digits? If so, what is the minimum/maximum number of digits? Are the digits always followed by a period? Is the period always followed by a letter? If so, what are the valid letters and are they always lower case? Also, how is that reference supposed to be modified to a URL? I.e. what would the URL look like for your example of '105.f'? Here is an example function insertReferences($text) { return preg_replace("#(\d{3})\.(\w)#is", '<a href="displayArticle.php?id=${1}&type=${2}">${1}.${2}</a>', $text); } //Text from DB $articleText = 'Beginning text and then a reference 105.f to another article'; //Modify text to include hyperlinks $outputText = insertReferences($articleText); //Output the result echo $outputText Output: Beginning text and then reference <a href="displayArticle.php?id=105&type=f">105.f</a> to another article
-
Please read requinix's earlier response. If you are still getting the full output with your code above, that is because the function wpjm_the_job_description() is outputting the content to the page and not returning it. E.g. wpjm_the_job_description() { $value = "Get some text from some process or source to be displayed"; echo $value; //The function is directly outputting text to the page return; //Nothing is returned from the function for you to modify it } You will either need to see if there is a function to get the string rather than outputting it or you can try modifying that function directly.
-
How to split a search strings and put it into a prepare statement?
Psycho replied to bbmak's topic in PHP Coding Help
If you want to do this with mysqli, there is a comment in the documentation with an example class: http://www.php.net/manual/en/mysqli-stmt.bind-param.php#109256 But, PDO is the way to go.- 6 replies
-
- search string
- split
-
(and 1 more)
Tagged with:
-
Select & checkbox values don’t show up in submitted form
Psycho replied to ThatGuyRay's topic in PHP Coding Help
To add to benanamen's response, it is not valid HTML markup to have multiple elements with the same id as you have with the checkboxes. The id for each element must be unique. <select id="choose" name="choose"> $vehicles = implode(', ', $_POST['vehicles'] ); $choose = $_POST['choose']; -
Where do you put opening curly braces when defining a method?
Psycho replied to NotionCommotion's topic in PHP Coding Help
Someone asked a similar question a long time back and someone pointed them toward the PSR coding standards. So, that's another option: http://www.php-fig.org/psr/psr-2/ -
What IS the problem? What are you expecting the code to do and what is is actually doing? One potential problem is that you have a scenario in which no value would be defined. But, since I have no clue on how your conditions are generated I have no idea if that is your problem. As to your code, my first suggesting is to stop injecting a mass of PHP logic into the HTML like that. Put your PHP logic at the top of your script and generate the dynamic content into a variable. Then output that variable in the HTML. EDIT: I do see a couple possible errors in your code. Look at the comments in the below revision example Example: <?php //Create code to determine value of the input field if (isset($_SESSION['user'])) { //This scenario ASSUMES that fname_bill is set, but the condition only tested //to see if user index in the Session is set. $firstnameValue = $curd->word($userRow['fname_bil'], 'UTF-8'); } elseif (!empty($_SESSION['auto_fill']['bil_adr'])) { //The condition is checking if the array index is NOT SET, but then //you try to reference that array index in generating the value $firstnameValue = $crud->word($_SESSION['auto_fill']['bil_adr']['cos_fis'], 'UTF-8'); } else { //Your original code had no logic to set the value based on neither //of the above two above conditions being true $firstnameValue = "?????"; } ?> <html> <body> <input type="Text" name="sen_add_dat_bil_fir" maxlength="200" required="True" placeholder="Firstname" value="<?php echo $firstnameValue; ?>"> </body> </html>
-
<?php $recordsPerPage = 24; $adPosition = 12; $limitStart = $recordsPerPage * ($pagenumber - 1); $sql = "SELECT * FROM content WHERE `live` LIKE '0' AND '{$today}' > `date` ORDER BY date DESC LIMIT {$limitStart}, {$recordsPerPage}"; $result=mysql_query($sql); $recordCount = 0; while($rows=mysql_fetch_array($result)) { //Increment the counter $recordCount++; //Code to display the current record goes here ## ## //Check if this is the 12th record if($recordCount == $adPosition) { //Code to display the ad goes here ## ## } } ?>
-
I agree with Jacques1. You really need to put some time into learning better practices. This is all very basic stuff. But, I'll be very generous and point out some of the problems. 1. Do not use the mysql_ extensions. They are no longer supported. You should be using mysqli_ or, better yet, PDO for database operations. 2. You should be using prepared statements for your queries with placeholders for any variable values in the query. This will prevent SQL injection (such as you are having). NEVER put user entered data directly into a query 3. You appear to be storing the password as plain text. Could you please provide me a list of any websites that you work on now and in the future so I can be sure to never sign up on them? </sarcasm>. You need to store the password as a hash. Then at login, hash the user input password and compare it to the stored hash. Do not use a simple MD5() or other hash. Use the built in PHP functions [password_hash() and password_verify()] or a properly vetted framework such as phpass. 4. I don't even know what this line is supposed to do. It should produce an error and even if it didn't the intent is unclear. I think you are trying to store a session value related to the password. There is no good reason to do this. hash($_SESSION["pass"] = $row['pass']; //<== Where's the closing paren??? 5. The is_array() check is meaningless. An empty result set would still return an (empty) array. You shoudl instead check if there was a record returned, Here is a resource to get you started on using the PDO extension and prepare queries: https://phpdelusions.net/pdo
-
You have duplicate data for 'text' and 'value' in each record for your example array, so I'm not sure which one you are wanting to use. Modify as needed foreach($productArray as $idx => $product) { echo $product['text'] . "<br>\n"; }
-
I'm sure you could do it with a query, but I think it would be complicated. Similar to determining a "rank", but you would have to keep track of win counts and start end dates. How many records will be applicable to any one request? If it is not really huge, just pull all the relevant records and determine the win streaks when iterating over the results. Not tested, but I think the logic is sound //Run query for all the records ordering by date // - 'win' will be a Boolean (1 or 0) $query = "SELECT date, (pointsfor > pointsagainst) as win FROM table_name ORDER BY `date` ASC"; $sth = $dbh->prepare($query); $sth->execute(); $result = $sth->fetchAll(); //Variable to hold the longest streak data $longestStreakCount = 0; $longestStreakStart = ''; $longestStreakEnd = ''; //Variable to track 'current' streak counts $currentStreakCount = 0; foreach($result as $row) { //Check if current record IS a win if($row['win']) { ## CURRENT RECORD IS A WIN //If first win, set start date for current streak if($currentStreakCount==0) { $currentStreakStart = $row['date']; } //Increment the win count for current streak $currentStreakCount++; //Set a 'lastWinDate' (used to determine the end of streak after 1st loss) $lastWinDate = $row['date']; } else { ## CURRENT RECORD IS NOT A WIN //Check if $current Streak is greater than the longest streak so far if($currentStreakCount > $longestStreakCount) { //Set new values for longest streak $longestStreakCount = $currentStreakCount; $longestStreakStart = $currentStreakStart; $longestStreakEnd = $lastWinDate; } //Reset current streak count $currentStreakCount = 0; } }
-
Join two tables, but only get single results from other table
Psycho replied to Strahan's topic in MySQL Help
Use MAX() to get the last date alone with a GROUP BY clause SELECT m.fileid, m.filename, MAX(w.watched) as last_watched FROM media m LEFT OUTER JOIN watchlog w ON m.fileid = w.parent WHERE m.parent = 6816 GROUP BY m.fileid ORDER BY filename -
There was a typo. User this: $selector = (isset($_GET['selector'])) ? $_GET['selector'] : false;
-
mac_gyver's solution is a good one too. One benefit of that solution is that you can easily change the options without having to touch the code/logic. You could even put the data in a separate (included) file. One assumption that he made in his example is that the passed value will necessarily be the value at the end of the URL and that all the URL will have the same base content. I would not make that assumption. Here is a revision of his code with some comments. // Define the choices in a data structure // This array can be defined at the top // of the page or in an included file $choices = array( 'airflow' => array( 'href' => '/folding-beds/browse-by/airflow', 'text' => 'Beds with Airflow Fibre Mattresses' ), 'deluxe' => array( 'href' => '/folding-beds/browse-by/deluxe', 'text' => 'Deluxe Collection' ), 'supreme' => array( 'href' => '/folding-beds/browse-by/supreme', 'text' => 'Supreme Collection' ) ); //Define the selection based on passed url parameter (or false if not set) $selector = isset($_GET['selector']) ? $_GET['selector'] : false; //Check if there is a value in the defined array for the $selector //If not, define the first key as the selector if(!isset($choices[$selector])) { $selector = key($choices); } //Define the text and href using the selector $href = $choices[$selector]['href']; $text = $choices[$selector]['text'];
-
Use this $label = trim($label['name']); Code should be separated based on its logical function/purpose. I would first start by separating the logic (i.e. PHP code) and the presentation (i.e. HTML content) into separate files. The presentation should just have code to output PHP variables that were generated within the logic. For new/casual programmers it is easiest to first start with what I proposed above - putting all the logic at the top of the script. In my opinion, people new to programming find it difficult to conceptualize the entire process when dealing with multiple, independent files and it is easier to work with a single field that creates the complete page. As you gain experience you should start moving any logic that is used on multiple pages into separate file(s). For example, if you make database calls, you should have a single file that creates the database connection. If you create multiple select lists dynamically, I would create a function that accepts tow parameters (an array with the value/label and (optionally) the currently selected value) and that function can build and return the HTML content for those select options. Once you have a better understanding of using multiple files, classes, etc in development then you can start using an MVC framework or something similar.
-
Better is subjective. If you are only going to have a couple of options then a single if/else condition is fine. You don't need two conditions for 'airflow' and '' since you want them to do the same thing. But, if there will be more options - or if you think it may grow, a switch() condition may be better. However, one problem I do see is that there is nothing defined in the case where 'selector' is not passed or if it does not equal one of those three values. Examples below Option 1 (only two end results): if(isset($_GET['selector']) && $_GET['selector']=='supreme') { $href = '/folding-beds/browse-by/supreme'; $text = 'Supreme Collection'; } else { //Values if 'selector' not set or does not equal 'supreme' $href = '/folding-beds/browse-by/airflow'; $text = 'Beds with Airflow Fibre Mattresses'; } Option 2 (if there will be multiple results): //Need to define value conditionally on if it is set to prevent //error referencing undefined value $selector = (isset($_GET['selector']) ? isset($_GET['selector'] : false; //Switch statement to define different conditions based on $selector value switch($selector) { case 'supreme': $href = '/folding-beds/browse-by/supreme'; $text = 'Supreme Collection'; break; case 'deluxe': $href = '/folding-beds/browse-by/deluxe'; $text = 'Deluxe Collection'; break; //If $select = 'airflow' or default: if did not meet any previous conditions case 'airflow': default: $href = '/folding-beds/browse-by/airflow'; $text = 'Beds with Airflow Fibre Mattresses'; break; }
-
His point is that (if the application is properly built) exposing the ID should not pose a security threat. If so, the application should be fixed rather than relying upon obfuscation as security.
-
What is this supposed to be doing? $lender_list = ($lender_list); Pro tip: create your logic (i.e. the core PHP code at the top of the script. Then output within the HTML at the bottom of the script. <?php //PHP Code at the TOP of the script //Create variable to hold the lender options $lenderOptions = ''; //Iterate through the array of lenders foreach($lender_list as $value => $label) { //Trim the value $label = trim($label); //If label is empty skip this record if(empty($label)) { continue; } //Create new option for the current lender $lenderOptions .= "<option value='{$value}'>{$label}</option>\n"; } ?> <html> . . . . <select name="some_field_name"> <?php echo $lenderOptions; ?> </select> </html>
-
So, is the scenario that the user selects to edit a record, but then decides they don't want to edit that record and wants to go back to the list of records? For that scenario, I typically implement a "Cancel" button on the edit form that will take the user back to the selection screen. Since your selection list is apparently based on a prior criteria input you could save that input as a session value. Then, clicking the cancel button will pull the search value from session and regenerate the selection list.
-
Take a look at this article about optimizing CSS: https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery#example Basically, you define the critical styles in the document (e.g. using script tags) and you dynamically load/apply the non-critical styles after the page has loaded. For the JQuery API - I'm not sure. There is an onload() event handler for JQuery - but the JQuery needs to already be loaded, which kind of defeats the purpose. Try taking a look at the 3rd response on this post: http://stackoverflow.com/questions/19026345/load-jquery-after-the-page-is-fully-loaded Depending on how the site is built this could be easy or difficult. If some things are 'required' to be loaded when the page is first rendered, it may take time to figure out all those pieces and/or could require some re-engineering. Good luck.
-
Wow, you are all over the place. You've completely deviated from your original example of $array[7][2] (which should have been $array[7]['types'][2]) to $royal_list[5] ['types'][8] So, I'm not following why the indexes are changing or how you determine which ones to use. But, assuming you know the correct indexes to use to reference the correct field, you need to know the exact types of values and the formats that will exist in that field. Your examples show a single numeric digit, followed by a space, followed by an alpha string, followed by a space, followed by a "percentage", followed by a space and finally another percentage. Are those percentages always a digit[period]three_digits? Although, I don't know if those are always spaces or if they are line breaks based on your first post. I can make some guesses on how to parse the value, but it really helps when I know all the possible values that could exist. Here is my best guess based on the limited information. function parseRateInfo($value) { if(!preg_match("#(\d*\s*\w*)\s*([^\s]*)\s*([^\s]*)#i", $value, $matches)) { //No match found return false; } //Parse the matches and return results $return['description'] = $matches[1]; $return['perc_low'] = $matches[2]; $return['perc_high'] = $matches[3]; return $return; } //Usage $value = "6 Month 3.140% 3.350%"; $rateInfo = parseRateInfo($value); print_r($rateInfo); Output Array ( [description] => 6 Month [perc_low] => 3.140% [perc_high] => 3.350% )
-
PHP Recursive Multidimensional Array to HTML nested code
Psycho replied to rod25's topic in PHP Coding Help
After creating your multi-dimensional array, you can use this to output the content. I put in logic to add spacing at each level to make it easy to "see" the structure of the HTML. <?php function createOutput($array, $level=0) { //Create variable to hold output $output = ''; //Create number of tabs for spacing the level $tabs = str_repeat (" ", $level); //Iterate through each element in the current level foreach($array as $record) { //Open div for the current record $output .= "{$tabs}<div id=\"{$record['id']}\">\n"; //Show current record name $output .= "{$tabs}\t{$record['tag']}\n"; //Check if there are children if(isset($record['children']) && count($record['children'])) { //Include children output $output .= createOutput($record['children'], $level+1); } //Close div for current record $output .= "{$tabs}</div>\n"; } //Return the results return $output; } ?> Output <div id="1"> div1 <div id="2"> div2 <div id="3"> div3 </div> <div id="4"> div4 </div> </div> </div> <div id="5"> div5 <div id="6"> div6 </div> </div> <div id="7"> div7 </div> -
No, that is true. But the first definition was for a larger group, whereas the second definition was for a smaller group. As an analogy, you might say all dogs will have a blue collar and then all Labradors will have a red collar. Any dog that is not a Labrador will have a blue collar. The second definition (which is more specific) has no impact on the non-Labrador dogs.
-
Thanks for the clarification Kicken. I guess my only objection would be due to my slight OCD with regard to storing "code" for what should logically be "data". I really didn't like the idea of storing custom tags either, but they at seemed more akin to data. I'll just need to create a process to parse the content into the format The {{ entities.product(123, "Widget", plaintext) }} is a new product ...
-
OK, here's the problem (I'll take some of the blame). In post #10 I stated (emphasis added) I meant for you to change/replace the existing definition for the 'active' class. Instead you added a new definition. So, the original definition that applied styles to the drop-down elements was still applicable. Here is part of what you just posted That last one should replace the first one.
-
Thanks for the response Jacques1, I think I am missing something in your response. Are you proposing I store the content as this: The {{ entities.product(123, "Widget", plaintext) }} is a new product ... These blocks of text will be saved in the database for many records. Think of it as a review for each product. The third parameter would have to be dynamic based on the purpose of the output. So, I assume I would define "plaintext" as a template variable (true/false) before executing the text with the twig code. Or maybe I am making some wrong assumptions in your response.