Grabbing more than just one row from DB - php

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

Related

Selecting and displaying data from the last 5 entries in a table

So, after searching for a while here in stack overflow, I found a way of doing it:`
$sql = "SELECT username FROM (SELECT * FROM users ORDER BY id DESC LIMIT 5) sub ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
echo $row[0];`
However when I echo the $row[0] to get the first entry it doesn't display anything. I have checked my connection to the database and used the query on the phpmyAdmin and it worked fine, not sure why isn't it displaying the data (There is also a user in the table with the ID 1).
mysqli_fetch_assoc returns an associative array, not a numbered array. So the index of each column in the result is the column name, $row['username'].
If you want all 5 usernames, you need to call it in a loop. Each call just returns one row of the results, not all of them at once.
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . '<br>';
}
To get a numbered array you use mysqli_fetch_row(). You still need the loop to get all of them.
while ($row = mysqli_fetch_row($result)) {
echo $row[0] . '<br>';
}

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

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.

shuffle : Display only one row at the same time

How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
Change your SQL request:
SELECT id,name FROM table ORDER BY RAND() LIMIT 1;
You can do it using PHP:
....
shuffle($rows);
$randomRow = reset($rows);
....
But the better way is to change your SQL query:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.
The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.

PHP - how to print each row of an array

I feel like I'm missing something really simple here. Here's my sql query:
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
I then print the first result:
echo $row[0];
And get a correct value, the id of the first page (by page order):
10
So I submit a form which simply turns that $row[0] into $row[1].
And nothing prints. I don't understand.
You have to do this:
while ($row = mysqli_fetch_array($showpages, MYSQLI_NUM)) {
$id = $row[id];
// do something with the id
echo $id . "<br/>"; // Echo every id
}
This will iterate through all of the results
mysqli_fetch_array is a special function as each time you call it, it outputs the NEXT row.
So:
while ($row = mysqli_fetch_array(stuff)){
$var = $row['sql column'];
// In your case "$var = $row[0];" to get the id for the first row found.
}
is how you use it.
This will keep running the function until mysqli_fetch_array() eventually returns false. These each time it will output a new row. And the $row array is the array of one row in the sql table.
Use :
print_r($row);
in the while loop to see exactly what's being returned for use.
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
Question how many rows are fetched in this query in this case id, So MYSQL will result to 1 row affected, But since you are using
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
This code you used will not output anything try
$row[n] as n-1
$result->fetch_assoc() or mysqli_fetch_assoc($result)
catch one line at a time, from a mysqli_result:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
source: http://www.w3schools.com/php/php_mysql_select.asp

Categories