Jump to content

Recommended Posts

Hi - I have written code that populates a dropdown from my table.I call this code quite a few times over my app and was wondering is that somewayI can turn this in to a function? I don't know if returning 2 arrays is the right way to go.Looking for suggestions.

 

$sQuery   = "SELECT * FROM `drop-business-categories` ORDER BY `item` ";
$iResult  = $mysqli->query($sQuery);
$iNumRows = $iResult->num_rows;
$iCount   = 0;
if ($iNumRows > 0)
{
  while ($iRow = $iResult->fetch_row())
  {
   $sArrayAllCatID[$iCount]   = $iRow[0];
   $sArrayAllCatItem[$iCount] = $iRow[1];
   $iCount++;
  }
}

Link to comment
https://forums.phpfreaks.com/topic/271482-creating-a-function-question/
Share on other sites

When I'm doing drop-downs, I return an associative array, with the database unique ID as the key and the value as the, well ... value.

 

function dropdownList($dbConn, $table, $idCol, $valueCol) {
 $sql = "SELECT $idCol, $valueCol FROM $table ORDER BY $valueCol";
 $res = $dbConn->query($sql);
 if (! $res) {
   # For development ...
   trigger_error('dropdownList query failed with error: ' . $dbConn->error() . ' -- ' . $sql, E_USER_ERROR);
   # ... in Production we need to handle the error or return an empty array
   return array();
 }
 $out = array();
 while ($row = $res->fetch_assoc()) {
   $out[$row[$idCol]] = $row[$valueCol];
 }

 return $out;
}

 

Disclaimer: Off the top of my head. Not Tested

 

To use the data:

 

$list = dropdownList($mysqli, 'Categories', 'ID', 'CategoryName');

$html = '<SELECT name="category">';
foreach ($list as $id => $value) {
 $html .= '<OPTION value="' . $id . '">' . htmlspecialchars($value) . '</OPTION>';
}
$html .= '</SELECT>';

echo $html;

 

Something like that

This is probably a dumb question, but the id can be any numeric value so how would I set this up?

 

 while ($iRow = $iResult->fetch_row())
{
$array[$iRow[0]] = $iRow[1];
}

Edited by PFMaBiSmAd
added quote, since the forum software post notification is pointless since it doesn't work the way forum's are used
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.