This question already has answers here:
How can I use PDO to fetch a results array in PHP?
(2 answers)
Closed 2 years ago.
I'm trying to echo out all the rows of a table using PDO but am running into trouble.
With the old way of doing I'd have done it like
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)){
$title= $row['title'];
$body= $row['body'];
}
But with PDO I'm trying;
$result = $db->prepare("SELECT title, body FROM post");
$result->execute();
while ($row = $db->fetchAll(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
echo $title;
echo $body;
Which keeps giving me Call to undefined method PDO::fetchAll()
Doing the example given in the manual
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
Works, but I don't think I have control over the individual colums like I would with a $row=['blah']; do I? It also prints out like this; rather ugly:
Array ( [0] => Array ( [title] => This is the test title entered in the database[0]
What needs to be done to properly use PDO to do this?
change:
while ($row = $db->fetchAll(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
to:
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
Which keeps giving me Call to undefined method PDO::fetchAll()
This should have given you the hint, that you are using the wrong object. It's PDOStatement::fetchAll as you can see in your second example, or if you want to use it in a while loop PDOStatement::fetch:
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
Additional notes:
$result is a misleading variable name as you might see from the $result->execute() line. You don't execute a result, you execute a statement. This is why in the manual $stmt or $sth (statement handle i guess) are used.
The echo lines should be inside the while loop, otherwise you overwrite again and again, then output only the last row.
Related
I want to fetch data from the database and use the first row initially. Then later if some values are true I want to loop through all of the rows.
The problem is that the while loop starts at the second row.
Is there a way to make the loop start at the first row?
Below is simplified example:
<?php
//GET THE CONNECTION DATA FOR $CONNECTION
require_once('../connect.php');
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => 'john#doe.com']);
$data = $get_data->fetch();
echo $data->email;
echo '<br>';
while($data = $get_data->fetch())
{
//STARTS AT THE SECOND ROW BUT NEEDS TO BE THE FIRST ROW
echo $data->last_name;
echo '<br>';
}
Yes you can use fetchAll()
$results = $get_data->fetchAll ();
$data = $results[0];
echo $data->email;
echo '<br>';
foreach($results as $data) {
//...
}
If you need something like this, you are doing something wrong.
For the question stated in the title, Dharman's answer is correct and should be accepted for sake of future visitors.
However, in your particular case, you don't need the first fetch and most likely don't need a while loop.
The first fetch is not needed because it is used to output the data you already have (the email used to query the database).
The while loop is not needed because most likely there is only one record in the database with such email, so you can just echo the username right away.
Either way, a sane version of your code would be either
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => 'john#doe.com']);
$data = $get_data->fetch();
echo $data->email;
echo '<br>';
echo $data->last_name;
echo '<br>';
or (in case your query indeed returns multiple rows)
$email = 'john#doe.com';
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => $email]);
echo $email;
echo '<br>';
while($data = $get_data->fetch())
{
echo $data->last_name;
echo '<br>';
}
See - you never need to "restart" the while loop.
This question already has answers here:
mysqli query results to show all rows
(4 answers)
Sql array only showing first result
(4 answers)
Closed 5 years ago.
I have write these kind of codes multiple times and it always worked great but now that I am on a different system it shows only 1 result.
the query is simple
$HOST = 'localhost';
$USERNAME = 'root';
$PASSWORD = '';
$DATABASE = 'db_test';
$con = mysqli_connect($HOST,$USERNAME,$PASSWORD,$DATABASE);
$sql = "SELECT * FROM test ";
$res = mysqli_query($con,$sql);
$res_array = mysqli_fetch_assoc($res);
echo json_encode($res_array);
mysqli_free_result($res);
mysqli_close($con);
I wonder if there is any settings that I have to change before running the app
Seriously, it's all over the docs:
mysqli_fetch_assoc Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
Note "the fetched row" part.
You need to do put your gathering in a cycle
$rows = [];
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row
}
json_encode($rows);
This line $res_array = mysqli_fetch_assoc($res); will only fetch one record.
You need to loop over result-set object and get all data from that.So use while() loop like below
$res_array =[];
while($row = mysqli_fetch_assoc($res)){
$res_array[] = $row;
}
Reference:-
mysqli_fetch_assoc()
Replace this line
$res_array = mysqli_fetch_assoc($res);
with
while ($row = mysqli_fetch_assoc($res)) {
$res_array[] = $row;
}
I am trying to query a db for an entire column of data, but can't seem to get back more than the first row.
What I have so far is:
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_fetch_array($medicationItemObj, MYSQLI_NUM)){
echo count($row);
}
It's not my intention to just get the number of rows, I just have that there to see how many it was returning and it kept spitting out 1.
When I run the sql at cmd line I get back the full result. 6 items from 6 individual rows. Is mysqli_fetch_array() not designed to do this?
Well, I had a hard time understanding your question but i guess you are looking for this.
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
if($row = mysqli_num_rows($medicationItemObj))
{
echo $row;
}
Or
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
$i = 0;
while ($row = mysqli_fetch_array($medicationItemObj))
{
$medicationItem[] = $row[0];
$i++;
}
echo "Number of Rows: " . $i;
If you just want the number of rows i would suggest using the first method.
http://php.net/manual/en/mysqli-result.num-rows.php
You can wrote your code like below
$medicationItem = array();
$medicationItemSql = "SELECT medication FROM medication";
$medicationItemObj = mysqli_query($connection, $medicationItemSql);
while ($row = mysqli_fetch_assoc($medicationItemObj))
{
echo $row['medication'];
}
I think this you want
You could give this a try:
$results = mysqli_fetch_all($medicationItemObj, MYSQLI_NUM);
First, I would use the object oriented version of this and always use prepared statements!
//prepare SELECT statement
$medicationItemSQL=$connection->prepare("SELECT medication FROM medication");
// execute statement
$medicationItemSQL->execute();
//bind results to a variable
$medicationItemSQL->bind_result($medication);
//fetch data
$medicationItemSQL->fetch();
//close statement
$medicationItemSQL->close();
You can use mysqli_fetch_assoc() as below.
while ($row = mysqli_fetch_assoc($medicationItemObj)) {
echo $row['medication'];
}
I'm trying to execute a statement where it will show all of the results for each row of my table but all it is doing is showing the results from the last row.
<?php
require_once('php/dbconfig.php');
$stmt = $DB_con->prepare("SELECT * FROM users");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = array($row['user_name']);
$email = array($row['user_email']);
}
echo $name[0];
?>
This will work but it will only echo out the name of the last person in my table. If I try to replace the 0 with any other number nothing will show.
I would like to be able to show all users and emails in a list.
In the following block you are assigning each name to the variable $name.
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = array($row['user_name']);
$email = array($row['user_email']);
}
I think you intend to either echo $name each iteration of the loop by adding the echo to the loop as:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = $row['user_name'];
$email = $row['user_email'];
echo "{$name} - {$email}";
}
or to add it to an array of names by changing the assignment from $name to $name[] which means 'the next index of the $name array'.
Fetch also returns one record, so you'll need to loop the results or change to fetchAll as suggested by other answers.
This question already has answers here:
mysqli prepared statement with while loop
(2 answers)
Closed last year.
Is it possible to do something like we do in normal mysqli queries in prepared statements in while lopping.
For example
$sql = "SELECT * FROM users"*;
$query = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($query)){
echo $row['username'];
echo $row['name'];
}
In prepared statements, it goes like this
$fetch_comments = $friend_zone->prepare("SELECT item_poster, comment FROM status_comments WHERE status_id = ? and item_poster = ?");
$fetch_comments->bind_param("is", $status__id, $item_poster);
$fetch_comments->execute();
$fetch_comments->store_result();
$fetch_comments->bind_result($item_poster_fetched, $comment_fetched);
while($fetch_comments->fetch(){
echo $item_poster;
}
What i mean is i want to do the echo like so
echo $row['something'];
The solution i came up with now is to fetch them using bind result, then put them into an array inside the loop and then foo['bar']; or something of that sort.
Is there a better way?
Doesn't this work?
$fetch_comments = $friend_zone->prepare("SELECT item_poster, comment FROM status_comments WHERE status_id = ? and item_poster = ?");
$fetch_comments->bind_param("is", $status__id, $item_poster);
$fetch_comments->execute();
$result = $fetch_comments->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['something'];
}
You're almost there with your code. You just need to assign the value to $row within the while loop's condition check:
while( $row = $fetch_comments->fetch() ) {
echo $row['somefield'];
}
The data is now bound to the $item_poster_fetched variable from what I understand...
while($fetch_comments->fetch())
{
$item_poster_fetched['something'];
}