Jump to content

Psycho

Moderators
  • Posts

    12,145
  • Joined

  • Last visited

  • Days Won

    127

Everything posted by Psycho

  1. <?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 ## ## } } ?>
  2. 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
  3. 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"; }
  4. 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; } }
  5. 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
  6. There was a typo. User this: $selector = (isset($_GET['selector'])) ? $_GET['selector'] : false;
  7. 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'];
  8. 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.
  9. 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; }
  10. 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.
  11. 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>
  12. 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.
  13. 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.
  14. 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% )
  15. 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>
  16. 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.
  17. 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 ...
  18. 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.
  19. 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.
  20. I would like to get some input on the below problem and my proposed solution. Is there a more efficient or elegant way to accomplish the requirements? I'm assuming others may have solved this previously and I see no reason to repeat other's mistakes if I can avoid them. Problem Statement: I am storing blocks of text that includes references to different 'entities' that will exists in the application. For my example below the entities are 'products' and 'companies'. I will have dual purposes for this text. In some cases, I will want to display the text as plain text (no html) and in others I will want those entities to be a hyperlink to view the record (or some other function). Also, I want the ability to change where those links go without having to modify the stored data. These 'entities' will be the only content within the text to need to use HTML. The Plan: My plan is to store the data with placeholders for the entities that include the entity type and the entity id. I can then use that data to either strip out the placeholder content (for plain text output) or dynamically create the hyperlinks using the entity type and id parameters. How I would store the text Example code <?php //Function to return plain text function outputPlainText($input) { //Strip out entity tags return strip_tags($input); } //Function to return text with hyperlinks function outputHtmlText($input) { //Find 'entity' tags and parse out parameters $pattern = "#<entity type='([^']*)' id='([^']*)'>([^<]*)</entity>#"; return preg_replace_callback($pattern, 'formatEntityLink', $input); } //Function to format hyperlinks function formatEntityLink($e) { //Format entity match as a valid hyperlink //** Actual logic would be more complicated //** Will probably use a switch statement for each entity type return "<a href='display_record.php?type={$e[1]}&id={$e[2]}'>{$e[3]}</a>"; } ?> Usage #1 echo outputPlainText($content); Output: Usage #2 echo outputHtmlText($content); Output:
  21. I used the EXACT same example page that I posted in post #7 with the change I provided on post #10. But, the snippet you posted on post #10 had changed the color. This is what I posted: li.active a.dropbtn { background-color: #990000; } This is what you posted li.active a.dropbtn { background-color: #f6f6f6; /* This set the background of the actively selected top menu item */ } Change it back.
  22. I guess I'm a little confused over why you changed the color of that property to gray. I thought you wanted the selected parent to be dark-red and the drop-down items to be gray. The change I made to the selector is to only apply the properties to the active' anchor tags with the dropbtn class - which would only be the parent item. When doing that I get the result below. Is that what you want?
  23. If you are having a problem with client-side code - please post client-side code. Without knowing what the output from the PHP code would be, it is difficult to replicate the issue and find a solution. Take the HTML source from a page where the problem exists and strip out everything that is not germane to the issue and post that. I tried to use the code above and replace dynamic content with values and my output looks very different from what you have posted. EDIT: I'm guessing you are using JQueryUI. The main element to output the content is nested in a div with the class 'slidingDiv' and your CSS has this for that class .slidingDiv { position: relative; display: none; } With that display: none; property the content doesn't get displayed. The JQueryUI is manipulating the CSS properties to display the content. So, it is impossible to know what the "real" properties are when viewed in the page from what you have provided. You could try creating a working JSFiddle page that displays the problem, then give us a link to that.
  24. You should typically not use a foreach loop to dump all fields out anyway. If you were to ever include a field in the query that should not be displayed - the user would see it. I think the code to output content should be explicit. having said that, it appears you want the output to be in a specific layout and not dynamic anyway. So, create a template using variables in the applicable fields. I can't tell from your code what the field names are since you are dynamically outputting the fields. But, here is an example with how it could look pulling a record using PDO <?php $query = 'SELECT invoice_no, paid, amount_paid, colour, size, print, embroidery, sew, supplier, customer, acknowledged From table_name WHERE invoice_no = ?'; $stmt = $pdo->prepare($query); $stmt->execute([$invoiceNo]); $record = $stmt->fetch(PDO::FETCH_ASSOC); ?> <table class="custom-data" cellspacing="0" cellpadding="4" width="100%" border="0"> <tr><td colspan="4" class="headline flush-left"><?php echo $form->getTitle(); ?></th></tr> <tr> <th>Invoice Number:</th><td><?=$recod['invoice_no']?></td> <th>Paid</th><td><?=$recod['paid']?></td> </tr> <tr> <th>Amount Paid:</th><td><?=$recod['amount_paid']?></td> <th>Colour</th><td><?=$recod['colour']?></td> </tr> <tr> <th>Size:</th><td><?=$recod['size']?></td> <th>Print</th><td><?=$recod['print']?></td> </tr> <tr> <th>Embroidery:</th><td><?=$recod['embroidery']?></td> <th>Sew</th><td><?=$recod['sew']?></td> </tr> <tr> <th>Supplier:</th><td><?=$recod['supplier']?></td> <th>Customer</th><td><?=$recod['customer']?></td> </tr> <tr> <th>Acknowledged:</th><td><?=$recod['acknowledged']?></td> <th> </th><td> </td> </tr> </table>
  25. The modification I posted two responses up should fix that. I was looking at the CSS and it could do with some clean-up, but I'm not the best person for that.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.