Reputation: 51
I am having difficulty getting Price and Date to display on the webpage.
Below is a section of the current code that I have. The MYSQLI_ASSOC part displays the correct data but the MYSQLI_NUM section of the code does not display at all. I am having trouble finding information on how to make it work.
<?php
$query = "SELECT ItemID, Name, Category, Price, Duration, Photo FROM
item ORDER by ItemID LIMIT 3";
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo "<br> Row: ". $row["ItemID"]. " - Name: ". $row["Name"]. "<br> " . $row["Category"] . "<br>" ;
}
} else {
echo "0 results";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_array(MYSQLI_NUM)) {
echo "<br> Price: ". $row["Price"]. " - Finish Time: ". $row["Duration"]. "<br> ";
}
} else {
echo "0 results";
}
?>
Upvotes: 1
Views: 129
Reputation: 4907
MYSQLI_NUM is the 'ordinal position' of a column, starting with 0 to the first column in the query results, 1 for the next column, 2 for the next, and so on. For example, if the 'Price' column appears first in the query results, it will be $row[0]
, but in your query, it is currently at $row[3]
. Otherwise, use the number that corresponds to the correct position of the query for the column.
See this for an example: http://php.net/manual/en/mysqli-result.fetch-row.php
Also, know that because your first loop cycles the recordset before your 2nd loop, you'll need to reset the list to avoid having to query twice.
if ($result->num_rows > 0) {
// output data of each row
$result->data_seek(0); // set the recordset back to the first row.
while($row = $result->fetch_array(MYSQLI_NUM)) {
MYSQLI_BOTH, which is the default, returns an array so that you can use the row results by column name OR by column number.
======
Know that many don't like using the column order numbers except for very small queries, like ones that return a single row, typically having only one column, such a count query. The reason is that if a larger query ever changes the column ordering, then the code has be 'scoured' to ensure that the column position numbers align/match to the updated query changes.
Upvotes: 1