Question-
I am updating an old reservation program as PHP? no longer supported. I have multiple select statements using output many times. Old code sample:
`$sql1 = "select route,fare,departure_time,from_location,arrival_time,to_location,notes,notice
FROM sectors2021
WHERE origin = '$origin'
AND destination = '$destination'
ORDER BY departure_time";
if ($result1 = mysql_query($sql1)) {
list ($route,$fare,$departure_time,$from_location,$arrival_time,$to_location,$notes,$notice) =
mysql_fetch_array($result1);
} else {
$message .= '\<p\>\<center\>Could not select from Sectors!\</center\>\</p\>';
}`
Returns Error: Fatal error: Uncaught TypeError: mysqli_fetch_array(): Argument #1 ($result) must be of type mysqli_result, string given in /xxxx/xxxx/xxxx/xxxx/publicbook.php:217 Stack trace: #0 /xxxx/xxxx/xxxx/xxxx/publicbook.php(217): mysqli_fetch_array('select route,fa...') #1 {main} thrown in /xxxx/xxxx/xxxx/xxxx/publicbook.php on line 217
Solution –
There are a couple of issues with the code you provided. Here’s a corrected version:
$sql1 = "SELECT route, fare, departure_time, from_location, arrival_time, to_location, notes, notice
FROM sectors2021
WHERE origin = '$origin'
AND destination = '$destination'
ORDER BY departure_time";
// FETCHING DATA FROM DATABASE
$result1 = mysqli_query($conn, $sql1);
if (mysqli_num_rows($result1) > 0) {
// OUTPUT DATA OF EACH ROW
while ($row = mysqli_fetch_assoc($result1)) {
$route = $row['route'];
$fare = $row['fare'];
$departure_time = $row['departure_time'];
$from_location = $row['from_location'];
$arrival_time = $row['arrival_time'];
$to_location = $row['to_location'];
$notes = $row['notes'];
$notice = $row['notice'];
echo "Route: $route";
}
}
The main changes are:
- Inside the while loop, you need to access the values from the
$row
variable that contains the current row’s data, instead of callingmysqli_fetch_array
again with the SQL query. - Each column from the result set needs to be assigned to a separate variable for later use.
- I added an
echo
statement to display the value of the$route
variable, which is only available inside the while loop.
Note that you should also make sure to sanitize user input before using it in a SQL query to prevent SQL injection attacks.