Reputation: 1386
So, this is an odd thing I have encountered and maybe it’s because of the late night or I am just missing something basic here. I have to send the query to array instead of looping over the query because other API calls can send the array instead of coming from the DB. The query returns multiple items as it’s supposed too. On to the code:
$result = $db->query("SELECT ID FROM tblTemp WHERE FOREIGN_KEY='2'");
$tmp = $result->fetch_array(MYSQLI_BOTH);
for($i = count($tmp); $i > 0; --$i) {
echo '<option value="'.$tmp[$i-1].'">Item '.$i.'</option>';
}
So, I am simply trying to get the array items into a HTML select. This works fine for passed $tmp arrays; however, what happens when you use the query is, that only the first record is populated in the select. The correct amount of items is added, but the values are missing. i.e.
<option value="">Item 2</option>
<option value="7">Item 1</option>
EDIT: PHP does throw an error of: Undefined offset: 1
Upvotes: 0
Views: 709
Reputation: 4221
Actually,
for($i = count($tmp); $i > 0; --$i) {
echo 'Item '.$i.'';
}
should work if $tmp returned the right amount. Ensure that $tmp returned the proper data.
Hope this helps.
Upvotes: 0
Reputation: 97727
You're only fetching one record from query, that's why you have one value and get an Undefined offset. In the following example a while loop is used to fetch all the results from the query.
$result = $db->query("SELECT ID FROM tblTemp WHERE FOREIGN_KEY='2'");
$html = "";
$i = 1;
while($tmp = $result->fetch_array(MYSQLI_BOTH)) {
$html = '<option value="'.$tmp['ID'].'">Item '.$i.'</option>'.html;
$i++;
}
echo $html;
Upvotes: 1