while loop for retrieving data - php

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"];
}
}

Related

array in foreach loop

I'm taking data from mysql database table. The table have ID and "POST" columns. I've ordered posts by id's from bottom so i always have the newest post on the first place. But when i want to echo specific post (eg. with id 5) i can't echo it with $col = mysqli_fetch_array($result); echo $col;. I've tried with foreach loop but it echo's all posts. So I thought if i could put them into array with foreach loop it would do the job.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
}
I've tried a lot of things and spent a lot of time on research but still don't have idea how to do it.
Thanks for your ideas and help.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
if($col['id'] == 5) {
print_r($col);
}
}
mysqli_fetch_array fetchs a result row as an associative, a numeric array, or both.
You need to specify the name of the column you want to print out.
Because you may have more than one row in your result set, you should use a loop (while) like so:
while ($row = mysqli_fetch_array($result)) {
echo $row['POST']; // 'POST' here is the name of the column you want to print out
}
Hope this helps!
UPDATED:
If you want to get a specific post, you have to change your SQL to something like this:
$sql = "SELECT * FROM `post` WHERE `id` = $wanted_post_id";

for each statement only returns the word 'Array'

I'm creating a personal advisor page with 3 advisors in my database, I'm trying to create a dropdown box where someone can choose which advisor they'd like. At the moment my dropdown only displays the word 'Array' three times. Here's what I have so far.
<select name="advisor">
<?
$sqlQ = "SELECT concat(firstName,' ',lastName) FROM adv WHERE advisor IS NULL";
$array=array();
$res = $db->prepare($sqlQ);
$res->execute();
echo("<option>Advisor</option>");
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$array[] = $row;
}
foreach($array as $info)
{
echo("<option>$info</option>");
}
Your $row is already an array, so no need to insert your $row into a new array. Just loop the results like this
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $info)
{
echo("<option>$info</option>");
}
}
// give the result of concat() an alias so you can easily access it in the result set
$sqlQ = "SELECT concat(firstName,' ',lastName) as name FROM adv WHERE advisor IS NULL";
[...]
while ( $row = $result->fetch(PDO::FETCH_ASSOC) ) {
// $row is an array, its members correspond with the fields/aliases you've selected
// apply htmlspecialchars() so that the contents of $row['name'] can't break your html structure
echo '<option>', htmlspecialchars($row['name']), '</option>';
}

Getting number of rows form SQL Server table

I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.

Grabbing more than just one row from DB

$sql = "SELECT title, article, filename, caption FROM articles
INNER JOIN images WHERE articles.image_id = images.image_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
var_dump($row);
This only grabs the first row in the db when what I need is for it to grab all rows. How can I achieve this?
fetch_assoc() returns the next row of the result set with each call, so you need to call it in a loop like this:
while($row = $result->fetch_assoc()) {
var_dump($row);
}
The loop ends when $row = null (i.e. there's no more rows in the result set).
Please have a look at the Quick start guide, more specifically the Executing statements chapter. Right from that page:
$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$res = $mysqli->use_result();
echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}

Drop down box filled with mysql rows php

I am currently working on a school project. My goal is to develop a dynamic web page that allows people to retrieve data from a database. I want to create a few drop down boxes that allows users to narrow down the data from my database I have created.
For example, I have "year" as one column in my database because I have gathered data from multiple years. I would like to establish a way for users to select a specific year by using an HTML drop down box. How exactly do I go about coding something like this using PHP and my database?
Here is my code so far, but I can't seem to get anywhere with this.
<select name='year'>
<?php
$query = "select distinct year from test order by year";
$result = $result->query($query);
while ($row = $result->fetch_assoc()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
?>
</select>
With this code, I am getting a drop down box, but no choices are given. It is blank. Any ideas? I would appreciate any help.
fetch_assoc() return the associative array not an object,should be accessed like array
$query = "select distinct year from test order by year";
$result = $result->query($query);
while ($row = $result->fetch_assoc()) {
echo "<option value='".$row['year']."'>".$row['year']."</option>";
}
<select name='year'>
<?php
$query = "select distinct year from test order by year";
$result = $result->query($query);
while ($row = $result->fetch_object()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
?>
</select>
To access the result as objects you should use fetch_object.
So your loop should change as below:
while ($row = $result->fetch_object()) {
Or use
$sql=mysql_query("select distinct year from test order by year");
while ($row = mysql_fetch_assoc($sql)) {
echo "<option value='".$row["year"]."'>".$row["year"]."</option>";
}

Categories