I am trying to retrieve multiple cars from a car rental database based on the model, so if someone clicks on Ford it would retrieve all cars that have a Model ID of 2 for example. The current code I have only shows the first record in the database, how do I make a while loop that would echo the rows for each match?
$ModelID = $_GET['model_id'];
$result = mysqli_query($con, "SELECT RegNumber, Colour FROM Car WHERE ModelID = '$ModelID'");
$row = $result->fetch_assoc();
echo $row["RegNumber"];
echo $row["Colour"];
You need something like:
while ($row = $result->fetch_assoc()) {
echo $row['RegNumber'];
echo $row['Colour'];
}
For more details, please go through the PHP Documentation
One possible solution is using mysqli::query. And never forget to escape data inside the query, in that case you should use mysqli::real_escape_string function
$escapedModelId = $mysqli->real_escape_string($ModelID);
$query= "SELECT RegNumber, Colour FROM Car WHERE ModelID = '$escapedModelId'";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row["RegNumber"];
echo $row["Colour"];
}
}