Custom Select Box for Large Data Lists (PHP, AJAX)

Posted by admin at December 30, 2016

inc/support.php

The script below is the most important function needed in this file. The function populates a select box with values from a MySQL table. Please see the tutorial here: Populating a select box with PHP/MySQL


/**
*
* function to generate the options of a select boxes
*
* $tbl          is the table to generate values from
* $opt_value    is the name of the column to use for the option value property
* $opt_text     is the name of the column to use for the option text property
* $rid          is the record id representing the selected option
* $conn         is the database connector resource
*
*/

function select_box($tbl, $opt_value, $opt_text, $rid, $conn, $opt_name='opt_src')
{
    // build the read query
    $sql = get_read_sql($tbl);

    // submit the query to generate rows
    $rs = mysql_query($sql, $conn) or die(mysql_error());

    // fetch the first 
    $row = mysql_fetch_assoc($rs);

    // calculate total rows
    $total_rows = mysql_num_rows($rs);

    // determine the selected option
    $sel = ($rid == 0) ? 'selected' : '';

    // initiate the options html
    $html = '<option value="0" '.$sel.'>--select--</option>';

   // loop through the result count
   for ($i=0; $i<$total_rows; $i++)
   {
      // if the current options is the selected
      // option then set the option's selected property 
      $sel = ($row[$opt_value] == $rid) ? 'selected' : ''; 

      // append the current options html 
      $html .= '<option value="$row[$opt_val]" '.$sel.'>'.$row[$opt_text].'</option>';

      // generate the next row
      $row = mysql_fetch_assoc($rs);
   }

   // return the html
   return $html;
}
   0 likes

Pages: 1 2 3 4 5 6


Suggested Read