Jump to content

mac_gyver

Staff Alumni
  • Posts

    5564
  • Joined

  • Days Won

    200

Community Answers

  1. mac_gyver's post in Speed an update loop up? (thousands of records) was marked as the answer   
    your overall processing is - insert new data, delete old data from groups having a size greater than the queue size (30)
     
    from fastest to slowest, the following is a list of ways to insert data -
     
    1) LOAD DATA INFILE query
     
    2) LOAD DATA LOCAL INFILE query
      3) a multi-value prepared INSERT query. you can dynamically prepare a single multi-value INSERT query with a block size to handle most of the data, then dynamically prepare a unique multi-value INSERT query to handle any final partial blocks of data.
     
    4) a multi-value non-prepared INSERT query
     
    5) a single value prepared INSERT query
     
    6) a single value non-prepared INSERT query
     
    if you can, write the new data to a file and use option #1 or #2. this will be about 20 times faster than using single INSERT query inside a loop.
     
    reusing a prepared query will save about 5%, over a non-prepared query. using a new prepared query each time will actually take longer. if you had a problem with using prepared queries, it was likely due to this. if you want help with your prepared query code, you would need to post it.
     
    a multi-value INSERT query can easily insert 5K -10K rows in a single query (the limit is the max allowed packet size between the client/php and the db server, default is 1M byte) and will be between 5-10 times faster than using a single INSERT query inside a loop.
     
    -------------------
     
    to do this, i would insert all the new data using the fastest method available, then as a second process, delete the old data item from each group that exceeds the queue size. for your current concatenated data, you can use a multi-value INSERT ... ON DUPLICATE KEY UPDATE ... query (rather than three queries) to concatenate new data items onto the end of the list, then after all the new data has been inserted/updated, you can use SUBSTRING_INDEX() in one single UPDATE query to remove any leading data item from the start of the lists.
  2. mac_gyver's post in stumped on a form was marked as the answer   
    only form fields that have name='...' attributes will be submitted, using the name attribute's value as the $_POST['...] variable's name.
  3. mac_gyver's post in Server 500 error migrating WordPress sites was marked as the answer   
    you need some white-space after any opening <?php tag. add a space, tab, or new-line.
     
    if a php tag is the first line in a file, i recommend always putting it as the only thing on the line, so that any errors can be pinned down to something before or after the tag.
  4. mac_gyver's post in How do I bind param in this query? was marked as the answer   
    in most cases, you don't need to explicitly bind parameters or values, just supply an array to the execute() method call.
     
    here are some points for your current code -
     
    1) the place-holder names must be unique. when you are dynamically building a prepared query statement, you should use ? place-holders.
     
    2) the place-holders do not get single-quotes around them in the sql query statement.
     
    3) when building similar terms, it is cleaner to build them in an array, then implode() the array with the separator keyword between the elements. this will work correct even if there is a single element.
     
    4) the sql query statement doesn't need ( ) around it and having them just clutters up the code.
     
    5) you should be using exceptions to handle statement errors. this will mean that your main code only has to deal with error free execution and you don't need to have conditional logic for each statement that can fail.
     
    6) if you use php's array functions, it will eliminate the need to explicitly loop in the code. see the following example - 
    $searchTerms = explode(' ', $search_string); // note: you should filter empty values out of the $searchTerms array and only execute the remainder of the code if there are any remaining values in $searchTerms // build the dynamic part of the sql query statement $terms = implode(' OR ', array_fill(0, count($searchTerms), "ci.item_name LIKE ?")); // produce the complete sql query statement $searchQuery = "SELECT ci.id, ci.item_name, ci.item_description FROM core_item ci WHERE $terms"; // prepare the query $searchStmt = $this->pdo->prepare($searchQuery); // function to add % wildcard characters to the value function _wildcard($val) { return "%$val%"; } // add the wildcard characters to the values $searchTerms = array_map('_wildcard',$searchTerms); // execute the query $searchStmt->execute($searchTerms); // fetch and return the result - this will be an empty array if the query didn't match any row(s) return $searchStmt->fetchAll();
  5. mac_gyver's post in look up table was marked as the answer   
    calculate how long it will take for your table to have 5 million rows in it. with today's server hardware, 5 million rows in a properly indexed table is about the point where you need to start worrying about doing things like using partitioning or archiving older data.
  6. mac_gyver's post in Cookie issue was marked as the answer   
    the code at the top of your post has - setcookie('hs_user_sess', $session, time() + (86400*30));, but there is no $session variable present in that code, so it would set the cookie to an empty value.
     
    also, break; only works for loops and switch statements. it has no affect on if() statements, so in the cases where you have used it in the code above, all the logic is still being executed.
     
    if your code testing if the cookie is set is being executed on the same page request where you are setting the cookie, the $_COOKIE variable won't be set until the browser makes a request to the web server after you have set the cookie.
  7. mac_gyver's post in newbee to PHP, help with setting up my php to send to a txt file was marked as the answer   
    the code on your page should be laid out in this general order - initialization, start of database dependent code, determine user state and permissions, post method form processing, get method business logic, end of database dependent code, get method presentation logic, and html docuement/template.
     
    1) initialization - create/define things your code needs - session_start(), require files holding configuration data/function definitions, setup an autoloader for class definitions...
     
    2) start of database dependent code - create a database connection.
     
    3) determine user state and permissions - check if the current user is logged in and retrieve any permissions the user has. the rest of the code on the page would make use of the logged in state and permissions to determine what code can be ran and what content will be produced.
     
    4) post method form processing - the post method form processing code, which causes an action or change in state or change in data values on the server, should come near the start of your file so that you aren't tempted to output anything to the browser before the action/state/or data operation has been performed by the processing code. if your page has multiple sections of form processing code, you would have them all groped together in this section of code.
     
    after successfully (no errors) processing any post data, do a header() redirect to the exact same url that the form submitted to. this will cause a get request for your page. this will cause the browser to forget that a form was just submitted to that url and it won't try to resubmit the form data if you refresh the page or browse back to the same url. this also enforces separation of concerns. post method form processing is a separate concern from displaying data due to a get request for your page. if you want to display a one-time 'success' message after the header() redirect, pass it in a session variable, then clear he session variable after the the message gets displayed.
     
    if there are errors while processing any post data, you would not redirect, stay on the page, let the rest of the code on the page display the errors, (re)display the form, and repopulate the form fields with (some of) the previously submitted values.
     
    5) get method business logic - code that produces/gets data needed for the dynamic content on the page. this code contains any database specific code that knows how to retrieve data from your database tables. the result of this code should be php variables that the code later on the page uses as its input. this code should contain NO html/css/javascript markup.
     
    6) end of database dependent code - you can (or let php do this when the script ends/exits) destroy any query result resources (to free up memory) and the database connection at this point since you won't need them any longer.
     
    7) get method presentation logic - code that knows how to take the data (database data, errors, form data...) from ALL the above code and produce the dynamic output for the page. if the output doesn't require any 'heavy' processing/formatting, just use the data directly in the html page/template code. the result from this code should be php variables that the html page/template uses. this code should contain NO database specific statements. if your page has multiple sections of get method presentation logic, you would have them all groped together in this section of code.
     
    html document/template - this section starts with the <!DOCTYPE ... tag and ends with the </html> tag. it is the actual html document that the dynamic output is put into to make the complete page. if you use php (rather than an actual template system) only simple php conditional logic/loops, function calls (that are responsible for producing output), and echo statements should be present in this section of code. any data you output on the page needs to be passed through htmlentities() in order to prevent any html content in it from being operated on by the browser.
     
    if you organize the code on your page like this, it will separate all the different concerns, making it easier to see what your code is doing, easier to test, and easier to get help with because you can isolate and post just the relevant part.
     
    next, if you put the form processing code and the form on the same page, it will reduce the amount of code you have to produce, since it will eliminate the repetition of the common items. this will also let you re-populate the form field values in the case where there were validation errors with the submitted form data.
     
     
    some specific comments for the code you have posted -
     
    1) the global keyword only has meaning when used inside of a function (which you are not doing) and even then it should be avoided as it breaks the encapsulation and scope. remove any lines of code containing the global keyword.
     
    2) if you use a php array variable to hold validation error messages, it will also serve as an error flag. if the array is empty(), there are no errors. if the array is not empty(), there are errors. after you have validated all the input data, you would use that data if there are not errors. at the point of (re)displaying the form, if there are errors, you would display them, either as a group or display them individually near the form field they go with.
     
    3) you should NOT be using addslashes() at all.
     
    4) whatever your validateInput() function code is, is probably not actually validating anything. if you want help with the validateInput() code, you need to post it.
     
    5) this is a bit tongue in cheek, but a person's age is not a fixed value, unless they are dead, and you should not be storing a person's age. you should be getting and storing the date of birth and then calculating the age when needed.
     
    edit: since you are using a file to hold the data, substitute 'file operations' for any mention of 'database' in the above information.
  8. mac_gyver's post in How can an index be set and undefined at the same time? was marked as the answer   
    the error is because you are concatenating the string 'count: ' with the isset() expression, which will always be true. you need to put () around the trinary statement so that it is evaluated as an expression that then gets concatenated with that string.
  9. mac_gyver's post in Updating Database changes all entries was marked as the answer   
    your code and queries are only as secure as you make them. if you use a prepared query incorrectly, it will won't be secure.
     
    by using a true prepared query (the PDO extension has emulated prepared queries turned on by default for all database types, despite what the documentation states, and you need to turn them off when you make the database connection) to supply data values to the sql query statement, your sql query will be safe against sql special characters in the data from breaking the sql syntax or breaking out of, i.e. escaping from, the sql syntax in the case of intentionally injected sql.
     
    after you choose the php database extension you are going to use, the posted code needs to do or not do a number of things -
     
    1) you are mixing procedural and OOP style for the msyqli statements. you should be constant in your programming. using the PDO extension will fix this since it only has OOP statements.
     
    2) using prepared queries will eliminate all the ...real_escape_string() calls. you are using one in the case of a value being output to the browser. the ...real_escape_string() statements are only used on string data being supplied to a non-prepared sql query statement, not on data being output to the browser.
     
    3) you need to use exceptions to handle database statement errors. your code has error handling on only one of the query statements now. the PDO extension already uses exceptions for connection errors. you need to set the error mode to exceptions, for all the rest of the statements, when you make the connection.
     
    4) all the post method form processing code should be grouped together and come near the top of your code. you should actually test if a post method form was submitted, then if you have multiple possible forms, detect a field name or field value that identifies if the Delete or Update form was submitted.
     
    5) you should validate all the submitted data before using it, then only use it if it is valid. use an array to hold validation errors. you can then test if the array is empty or not to determine if there have been any validation errors. to display the errors, just output the contents of the array.
     
    6) your delete checkbox logic only works for a single/last checkbox. in fact, all the form fields don't work when there is more than one set of data in the form. you need to use array names for all the form fields, with the $row['id'] value as the array index (this is needed to distinguish which row each form field value corresponds to) and you need to remove the hidden field with name='checkbox' (having this causes only the last checkbox in the form to work.) you would also need to add a loop in the Update form processing code to loop over all the submitted sets of data.
     
    7) with prepared queries, when you are looping over data and executing the query inside the loop, you will prepare the query once before the start of the loop. the code inside the loop only gets the correct set of data and calls the ->execute() method.
     
    when you remove the hidden form field with name = 'checkbox' (which was done to prevent php errors when no checkboxes are checked, but because it is being output repeatedly, only allows the last checkbox to work), the logic in the delete form processing code will need to be changed. if there are no checked checkboxes, $_POST['checkbox'] won't be set. you need to add an if(isset($_POST['checkbox'])) test.
     
    9) the code to retrieve the data needed to display the page should be removed from the actual html document/template. this will make it easier to write and test your code, and if you need to change the code to use a different database extension, such as the PDO extension, consolidates the database specific code in one place and makes the html document/template general purpose. just fetch the data from the query into a php variable and use that variable in the html document/template.
     
    10) the html document you are creating is reusing DOM id='...' attribute values. id's must be unique. if the client-side code isn't actually referencing the id's, don't even put them into the markup.
     
    11) you are outputting an empty <tr></tr> after each actual <tr>....</tr> of output. makes no sense and is repeating an id attribute value which is also not valid. only output markup that you need.
     
    12) you are outputting the $row['id'] value in a form field. this is not an editable data value. the $row['id'] specifies which row the data belongs to. you can display the $row['id'] value if you wan't, but it should not be in a visible form field. see item #6 in this list for how the $row['id'] value should be used to associate the submitted values with the $row['id'] value they belong to.
     
    13) when your SELECT query doesn't match any data, your code is correctly skipping over the code to produce the output from that data, but your code is also not doing anything to notify the user that there was no data to display. you should set up and display a message that the reason for the blank section on the page is that there is no data to display.
     
    14) all data values being output to the browser should be passed through htmlentities(), with an appropriate 2nd parameter value, to prevent any html entities in the data from breaking the html on the page and to help prevent cross site scripting.
     
    15) you are repeating the <tbody>...</tbody> tags for each set of data being output. while this is valid markup, unless you are going to style each table body section separately, there's no point in doing this and it is just adding clutter to the result and would prevent a large table body section from being able to be scrolled on the page.
  10. mac_gyver's post in sess_start() makes session variables vanish. was marked as the answer   
    did verifymail.php ever have a sess_start(); call in it?
     
    all your files must be doing the same thing for the session to match up. it's likely that this was initially working because you already had an existing session, using session_start(), that matched up between the files. when you added sess_start() to just the index.php page, that created a new session with a second name, alongside the existing session, and so your verifymail.php had session data. once you finally closed your browser and started over, index,php was using the sess_start() settings, verifymail.php was using the session_start() settings, and there was no matching session data for verifymail.php to use.
     
    most of the code you have shown at the top of index.php is common logic that ALL your pages should use. why don't you have them in a file and require it into each page (Don't Repeat Yourself - DRY) or better yet, if you are at the point of wanting to set up custom session settings, why aren't you using a single file, index.php, to implement your entire site? having a single index.php file site would eliminate the need to even pass data in session variables and would eliminate all the repetitive code and html you are trying to write, test, and maintain.
  11. mac_gyver's post in Process the value of a searched result was marked as the answer   
    do you have php's error_reporting set to E_ALL and display_errors set to ON in the php.ini (putting these settings into your code won't help show syntax errors in the same file where the settings are being set) on your development system so that php would help you by reporting and displaying all the errors it detects?
     
    you would be getting a php syntax error because you are mixing php and html markup inside of php code tags. you would also be getting a blank php page, which you didn't tell us you are getting as a symptom when you run your code. to output in-line html markup, you need to have a closing php tag to switch out of php 'mode'. with 300+ posts, you should be past having these basic problems.
  12. mac_gyver's post in What did I do wrong? was marked as the answer   
    an auto-increment column needs to be an integer data type.
  13. mac_gyver's post in How can i insert data from biomatric device to mysql + PHP was marked as the answer   
    it would be helpful if you define what the work-flow (steps) is (are) before you try to write code. it will also help us if you tell us what the work-flow is supposed to be. something like - 1) connect to device, 2) retrieve user and attendance data, 3) display data in forms, 4) submit form, 5) store submitted data into database table.
     
    are you displaying the data as part of the learning/debugging process and you want to 'automatically' insert the data into the database tables OR are you trying to display the data in a form and you will manually submit the form to cause the data to be inserted into the database tables?
     
    next, you need to separate the different concerns in your code.
     
    any form processing code should be near the top of your file and come before you output any html to the page. the form processing code would come before the <!DOCTYPE tag. all the form processing code would be grouped together.
     
    to display the page, your code is retrieving user and attendance data from the time-clock. the code to retrieve this data and store it in php variables should be grouped together and come before you start outputting the html document. you would then simply loop over this data when you output the html document.
     
    if you are outputting the data in a form, perhaps to allow it to be verified and edited by a manager, you would need to output it using form fields, in a valid form. there are currently no <form...> tag(s) and no data-input form fields in your code. your attendance data output doesn't even have a <table> tag, no <tr></tr> <td></td> tags and no echo statements for the data.
  14. mac_gyver's post in extract image data (BLOB) from imagejpeg() was marked as the answer   
    you would need to use php's output buffering statements.
  15. mac_gyver's post in incremental number for each table row was marked as the answer   
    actually, naming form fields (variables, db column names, or anything else) with an incremental number is a bad design that takes more code to produce the markup and process the data.
     
    you should use an array name for the form fields.  - name="School[]", name="Student[]", and name="Class[]".
     
    this will submit the data as a php array for those field names, that you can simply loop over and access the values from each set of form fields within the group.
  16. mac_gyver's post in insert a query after getting a query was marked as the answer   
    i recommend that you tell or show us what symptom or error you are getting that leads you to believe that something doesn't work. we are not sitting there with you and don't know what it is you are seeing in front of you.
     
    why are you using both the msyql and mysqli extensions in one script? do you even have a connection using the mysql extension? there would be php error's if you don't. do you have php's error_reporting set to E_ALL and display_errors set to ON so that php would help you by reporting and displaying all the errors it detects?
     
    your code should ALWAYS detect and handle errors with database statements, so that it doesn't try to run logic that's dependent on database statements working when they haven't and test to make sure that a query matched a row of data before using the data.
     
    why are you using a multi_query() statement for a single query? this opens the door for sql injection to run ANY type of query, especially since you are not doing anything to protect against sql injection. even if you currently trust the data source, someone at some point can get nefarious data onto the site you are getting your data from. you must ALWAYS protect against sql injection.
     
    btw - the php mysql extension has been removed from php for almost a year. you should not be using it at all at this point in time.
  17. mac_gyver's post in PHP Error - mysqli_result, boolean given was marked as the answer   
    return, the point where the sql syntax error is occurring at is a reserved mysql (database server) keyword. are you sure the original query wasn't as follows, with back-ticks around the table name - 
    "SELECT * FROM `return` WHERE nMemberID='$nMemberID' AND nInfoID='$nInfoID' ORDER BY nReturnID DESC"; next, just converting the mysql_ statements to mysqli equivalents is not enough. you must also safely supply data values to the sql query statement. if $nMemberID or $nInfoID are coming from external data or they could contain any sql special characters, they must either be properly escaped (see the mysqli real escape string function/method) or you need to use a prepared query with place-holders in the sql statement for the data values and then bind the actual data to the place-holders. a prepared query is actually the best choice since it is impossible for injected sql in the data to be treated as sql syntax, whereas using the escape string function must have the proper character encoding set for the database connection to match what the database tables are set up for.
  18. mac_gyver's post in Skipping first line of db was marked as the answer   
    look at your code, between where you are executing the sql query and where you are looping over the data from that query.
  19. mac_gyver's post in jQuery Sortable Portlet Save position to database was marked as the answer   
    so, i went through your code to figure out what it is doing, in order (pun intended) to figure out how to make this work.
     
    starting with your html markup -
     
    1) the id='...' attribute you have for the column div's, should start with a letter, to make them valid. i choose to use id='COL_n', where n = 1, 2, ..., 6
     
    2) the portlet div's needs an id attribute so that the serialize/toArray functions have something to use as data. i choose to use  id='ID_n', where n is the job id auto-increment column value from your database table (if you don't have a job id, you need one.)
     
    3) to allow the php code to dynamically produce the html, for the different status values 1-6, you need a way of mapping the status value to the display label - 'New' through 'To Be Invoiced'. i choose to use an array, and since you (probably) want to output each status section, regardless of if there is any data for it, you would loop over this array to produce the sections on the page, then loop over any data for each section.
     
    the html, from the <div style="clear:both;"></div> to the end of the page should look more like the following (note: data values that you output to the browser should be passed through htmlentities(). this is not in the example code and is left up to you as a programming exercise)  -  
    <?php // define status value to label mapping $status_map = array(); $status_map[1] = 'New'; $status_map[2] = 'Artwork Rec'; $status_map[3] = 'Approved & Ordered'; $status_map[4] = 'In Production'; $status_map[5] = 'Delivered'; $status_map[6] = 'To Be Invoiced'; // query for all the data you want, in the order that you want it $query = "SELECT * FROM jobs ORDER BY status ASC, job_title DESC"; $result = mysqli_query($con,$query); $data = array(); while($row = mysqli_fetch_assoc($result)) {     $data[$row['status']][] = $row; // index/pivot the data using the status value - 1..6 } // note: i used some made-up data in the $data array at this point. the above query code should work, but is untested. // loop over the data and produce the output foreach($status_map as $key=>$label) {     echo "<div class='column' id='COL_$key'>\n";     echo "<h3>$label</h3>\n";     if(isset($data[$key])) // is there any data from the database for this key/status     {         foreach($data[$key] as $row)         {             echo "<div class='portlet' id='ID_{$row['id']}'>\n";             echo    "<div class='portlet-header'>{$row['job_title']}</div>\n";             echo    "<div class='portlet-content'><a href='pdfs/{$row['pdf_link']}' target='_blank'>View PDF</a></div>\n";             echo "</div>\n";         }     }     echo "</div>\n"; } ?> </body> </html> next, the jquery you have that is using an id selector - "#portlet" should be removed since this exercise is operating on a class basis, not an id. also, you would not use the update : method, since this triggers for every column that gets updated. if you move something from one column to another, it triggers two times. you need to use the stop : method. see the following javascript/jquery that i came up with - 
      <script>   $(document).ready(function(){     $( ".column" ).sortable({       connectWith: ".column",       handle: ".portlet-header",       cancel: ".portlet-toggle",       placeholder: "portlet-placeholder ui-corner-all",         stop: function() {             var dat = [];             var i = 0;             $(".column").each(function() {                 dat[i++] = [this.id,$(this).sortable("toArray")]; // this.id is the column id, the 2nd element are the job id's in that column             });                          $.ajax({                 method: "POST",                 url: "save_order.php",                 data: { data: dat }             });         }     });     $( ".portlet" )       .addClass( "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" )       .find( ".portlet-header" )         .addClass( "ui-widget-header ui-corner-all" )         .prepend( "<span class='ui-icon ui-icon-minusthick portlet-toggle'></span>");     $( ".portlet-toggle" ).on( "click", function() {       var icon = $( this );       icon.toggleClass( "ui-icon-minusthick ui-icon-plusthick" );       icon.closest( ".portlet" ).find( ".portlet-content" ).toggle();     }); });   </script> this will submit an array of data to the .php file, in $_POST['data']. see the following example code that extracts the column number and job id (if any), and logs the information to log.txt -
    <?php // for some reason, the portlet toArray 'adds' an empty element to the start of each array if(isset($_POST['data'])) {     foreach($_POST['data'] as $arr)     {         //$arr[0] is the column id - COL_1, COL_2 (these are the status number 1-6 = New - To Be Invoiced)         //$arr[1] is an array of the ids that are in the column - ID_1, ID_5                  // get the status (column) number         list($not_used,$status) = explode('_',$arr[0]);                  // get the id's in each status/column         $arr[1] = array_filter($arr[1]); // remove empty elements         if(empty($arr[1]))         {             // an empty status/column             $str = "Status: $status, empty";             file_put_contents('log.txt',print_r($str,true)."\n",FILE_APPEND);         }         else         {             // non-empty status/column             foreach($arr[1] as $element)             {                 // get the id number                 list($not_used,$id) = explode('_',$element);                 $str = "Status: $status, Id: $id";                 file_put_contents('log.txt',print_r($str,true)."\n",FILE_APPEND);             }         }     } }
  20. mac_gyver's post in Hi, how to have jquery check if one of several select menus have quantity select allow submit... was marked as the answer   
    assuming that you want to look at all the select/option menus and they all have class='qty', you would loop over each of the elements with that class - 
    $(document).ready( function() {     $('input[type="image"]').click( function()     { var total = 0; $( ".qty" ).each(function() { total += Number($( this ).val()); });         if(total == 0)         {             alert("You have not selected a product quantity!");             return false;         }     }); });
  21. mac_gyver's post in mysql query not working with drop down boxes was marked as the answer   
    promised example code - 
    // define, or get from an sql query, the choices for the select/option menus $author_data = array(); $author_data[] ="ken davies"; $author_data[] = "arthur smith"; $author_data[] ="gill rafferty"; $author_data[] ="molly brown"; $author_data[] ="gilbert riley"; // define and populate the data for the other select/option menus. left up to you as a programming exercise. $genre_data = array(); $year_data = range(2002,2008); $publisher_data = array(); // define a list/array of expected inputs for the dynamic WHERE clause $choices = array(); $choices[] = 'author'; $choices[] = 'genre'; $choices[] = 'year'; $choices[] = 'publisher'; // produce the dynamic WHERE clause $and_terms = array(); // holds each term for the WHERE clause // loop over the defining array of choices foreach($choices as $choice) {     if(isset($_GET[$choice]))     {         // the choice is set, add it to the terms to use         $and_terms[] = "`$choice` = '$_GET[$choice]'"; // you need to either - validate that the input value is exactly one of the possible choices, properly escape the value using the database escape string function, or use a prepared query to supply the value to the sql statement. left up to you as a programming exercise.     } } // db  connection - convert to PDO and use exceptions to handle errors. left up to you as a programming exercise. $con = mysql_connect("localhost","root",""); If (!$con){     die("Can not Connect with database" .  mysql_error()); } mysql_select_db("authors",$con); $where_clause = !empty($and_terms) ? 'WHERE ' . implode(' AND ', $and_terms) : ''; // build the sql query statement $sql = "SELECT * FROM books $where_clause";      // execute the query and retrieve the data into an array $result_data = array(); $myData = mysql_query($sql,$con); while($row = mysql_fetch_assoc($myData)) {     $result_data[] = $row; } // start the html document/template  ?> <html> <head> <title>My Page</title> </head> <body> <br> <form> <select name="author" size="2"> <?php foreach($author_data as $value) {     $sel = isset($_GET['author']) && $_GET['author'] == $value ? ' selected': '';     echo "<option value='$value'$sel>$value</option>\n"; // you need to apply htmlentities() to any data being output. left up to you as a programming exercise. } ?> </select> <input type = "submit" value = "go"> <select name="genre" size="4"> <?php // use code similar to the above to produce each set of select/option choices. left up to you as a programming exercise. ?> <option value="adventure">adventure</option> <option value="biography">biography</option> <option value="crime">crime</option><br /> <option value="romance">romance</option> <option value="thriller">thriller</option> </select> <input type = "submit" value = "go"> <select name="year" size="4"> <option value="2002">2002</option> <option value="2003">2003</option> <option value="2004">2004</option> <option value="2005">2005</option> <option value="2006">2006</option> <option value="2007">2007</option> <option value="2008">2008</option>                                       </select> <input type = "submit" value = "go"> <select name="publisher" size="4"> <option value="blue parrot">blue parrot</option> <option value="yonkers">yonkers</option> <option value="zoot">zoot</option> </select> <input type = "submit" value = "go"> </form> <?php // you need to use css to style your table border. left up to you as a programming exercise. echo"<table border='3'> <tr> <th>id</th> <th>author</th> <th>title</th> <th>publisher</th> <th>year</th> <th>genre</th> <th>sold</th> </tr>"; foreach($result_data as $row) {     echo "<tr>";     echo "<td>" . $row['id'] . "</td>"; // you need to apply htmlentities() to any data being output. left up to you as a programming exercise.     echo "<td>" . $row['author'] . "</td>";     echo "<td>" . $row['title'] . "</td>";     echo "<td>" . $row['publisher'] . "</td>";     echo "<td>" . $row['year'] . "</td>";     echo "<td>" . $row['genre'] . "</td>";     echo "<td>" . $row['sold'] . "</td>";     echo "<tr />"; } echo "</table>"; ?> </body> </html>
  22. mac_gyver's post in Why Warning "Cannot modify header information" Is NOT Fired ? was marked as the answer   
    For the case you have just posted, php's output buffering is turned on in the php.ini or possibly .htaccess file (if php is running as a server module) on your server. You can determine this by looking at the output from a phpinfo() statement.
  23. mac_gyver's post in My code is broken *somewhere* was marked as the answer   
    textarea's don't have value='...' attributes. you output the existing content in between the <textarea>content goes here</textarea> tags.
  24. mac_gyver's post in Foreach loop doesn't bring all the records from the database was marked as the answer   
    setting php's error_reporting to E_ALL and display_errors to ON (which should already both be set this way in the php.ini on your development system), should help with finding the cause of the problem.
     
    does the 'view source' of the page show all the repeated sections of content? maybe there's a broken html comment or tag that's preventing the output from being rendered by the browser.
     
    also, does the content, that's after the end of the loop, get displayed?
  25. mac_gyver's post in looping results from query and limit amount per row was marked as the answer   
    you will also want to JOIN the image table, whatever its name is, with the products table, so that you can run just ONE query. and did you really name the database column catagory, rather than category?
     
    your code should look like this - 
    $items_per_row = 5; // number of items per output row $query = "SELECT p.id, p.catagory as category, p.name, p.make, i.name as imgName  FROM products p  JOIN $table3 i ON p.id = i.insert_id  ORDER BY p.catagory, p.make, p.name"; // execute query using PDO, $pdo contains an instance/connection to the msyql database server $stmt = $pdo->query($query); // pre-process the data and index it by category, creating an array of arrays with the main index being the category $data = array(); foreach($stmt as $row) {     $data[$row['category']][] = $row; } // produce the output from the data foreach($data as $category => $arr) {     // Create a table with an id name of the category     echo "<table width='100%' id='$category'>\n";     // Write the first row of the table - Category Title     echo "<tr><td><span class='catTitle'>$category</span></td></tr>\n";          // output the rows of data     $chunks = array_chunk($arr, $items_per_row);     foreach($chunks as $chunk)     {         echo "<tr>"; // start a new row         foreach($chunk as $row)         {             // Write new <td> in table with the data of the title             echo '<td width="20%" class="cellPadd"><a href="product.php?id=' . $row['id'] . '"><div class="latest"><div class="latestTop">';             echo "<img class='latestImg' src='images/listings/" . $row['imgName'] . "'  border='0' width='100%' />";             echo '</div><div class="latestBottom">';             echo $row["make"];             echo $row["name"];             echo "</div></div></a></td>\n";         } // complete a partial row         $count = count($chunk);         if($count < $items_per_row)         {             echo str_repeat("<td> </td>\n", $items_per_row - $count);         }         echo "</tr>\n"; // end the row     }     echo "</table>"; // end the table }  
×
×
  • 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.