What is the point of fetchAll? - php

To get the result from the database, you can do this:
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll();
foreach($result as $r) {
echo "<pre>";
print_r($r);
echo "</pre>";
}
but it seem to work without using fetchAll, example:
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$result = $sth->execute();
foreach($result as $r) {
echo "<pre>";
print_r($r);
echo "</pre>";
}
so what is the difference?

fetchAll will read in all rows from the database resultset and make an array out of them, keeping it all in memory. Iterating over the resultset will fetch one row at a time from the server which will save resources on the PHP side (but may use more resources on the database server, depending on the database implementation).

Firstly I assume that you are using php PDO
With fetchAll you can specify Fetch mode as an argument and fetchall provides more flexibility over the returned rows and fetchall will read all rows from database and translate into an array.
fetchall is lot more efficient in resource management compared to simple executes i guess. also the resource returned by execute is bool

Related

PHP Fetchall only returning column header

I have a database that I am trying to query to get information to display to my user. I have used
fetch(PDO::FETCH_ASSOC)
before when retrieving a single row or
$row = mysql_fetch_array($result)
with good results. However, it is my understanding that it is better practice to use PDO so that is what I am trying to do.
The problem I am running into is that my results are only showing me the first row of the data I need. In this instance it is displaying the column header over and over and never giving me the data.
$stmt = $conn->prepare("SELECT ? FROM application");
$stmt->bindparam(1, $application_ID);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
foreach($results as $row){
echo $row['application_ID'];
}
Here are the results
application_IDapplication_IDapplication_IDapplication_ID
It is good that you are aware that MySQL has been oficially deprecated and now we are supposed to used MySQLi or better yet, PDO.
Since you are not accepting any user input, there is no need of using a prepared statement.
Simply do this:
$stmt = $conn->query("SELECT * FROM application");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row){
echo $row['application_ID'];
//output other rows here
}
As per the php documentation pdo::fetchAll
you have to use fetchAll, instead of fetchall.

While loop to display all data after SELECT query

I know this might be a very basic question, but I am new to php and databases, I'm trying to figure out a while condition that will keep while loop running until all (would be also nice to know how to do it for fixed amount) of data is taken form database.
$stmt = $db->prepare("SELECT * FROM icecreams");
$stmt -> execute();
$row = $stmt -> fetchAll(PDO::FETCH_ASSOC);
So now I need to figure out what while condition I need, the logic is
while (there is data to fetch) {
echo "<h1>$row['flavour']</h1>";
echo "...";
}
fetchAll() returns an array containing all of the result set rows, whereas fetch() returns a single row from the result-set.
fetchAll() Usage:
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($array as $row) {
# code...
}
fetch() Usage:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
# code...
}
If you're going to use this for printing HTML, the second option seems nicer. For small recordsets, the performance difference shouldn't really matter, but if you're working with a lot of records, then fetchAll() might be a little slower, as it tries to map the entire data into a single array at once.
$stmt = $db->prepare("SELECT * FROM properties");
$stmt -> execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//$row['column_name']
}
fetchAll does fetch everything as an associative array (as flag FETCH_ASSOC tells). It does it automatically for, you don't have to worry about it.
If you do this then you will see that you have all of your data in an array already:
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<pre>'.print_r($row, true).'</pre>';
So now you can simply loop the items an access the data:
foreach($row as $k=>$v)
{
echo $k.'<br>'; // this will show you what row # you are on, sometimes useful :)
echo $v['title'].'<br>';
// etc....
}

(PHP) How do I return regular MySQL result resources when using prepared statements?

This is a bit of a clueless-beginner type of question, so I apologise. But I've not managed to find a website or video that helps me understand working with MySQL prepared statements, so I'm hoping for some direct advice.
For the last couple of weeks of my learning, I've been using procedural MySQLi calls to make database queries, and working through them with while loops. Things like
$query = mysqli_query("SELECT * FROM `Shoes` WHERE `Color` = 'Red'");
while ($row = mysqli_fetch_assoc($query)) {
echo $row['size'];
}
Things like that. It makes sense to me that I would be execute a query, get returned a special results resource, and then use a 'fetch_something' function to turn it into an array I can pick from and loop over, regardless of its size.
Now I'm trying to learn about prepared statements. What's tripping me up is the 'bind_result' function that seems to get used all the time, at least in every book and tutorial I've consulted so far. It tells me to provide one variable per column, to which the result for that column will be bound. Like
$db = new mysqli(server,user,pass,database);
$stmt = $db->prepare("select `Temperature` from `BuildingDetails` where `HouseNumber` = ?");
$stmt->bind_param("i",$_GET['num']);
$stmt->execute();
$stmt->bind_result($x);
$stmt->fetch();
echo "The temperature in this house is {$x}.";
Simple enough when I'm retrieving a single value, or a single row. But what if I want to loop over a table with 20 columns and 5,000 rows? Is there a way I can just return a regular old MySQL result resource and use fetch_assoc or something on it?
Is there a way I can just return a regular old MySQL result resource and use fetch_assoc or something on it?
You can use mysqli_stmt_get_result
Procedural
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result))
{
print_r($row);
}
OOP
$result = $stmt->get_result();
while ($row = $result->fetch_assoc())
{
print_r($row);
}
This way you do not have to bind all the variables to get results.

PDO equivalent of pg-result-seek

Anybody knows the PDO equivalent of pg-result-seek? I want to rewind a dataset using Postgre.
PDO's query() method will return a PDOStatement Object. There is no equivalent to seek to a specific record like you are asking. One alternative might be to use the fetchAll() method and then grab the Nth record you are looking for.
<?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);
$result[N] would contain the row you are looking for.
If Database Permits, Use PDO::FETCH_ORI_ABS or PDO::FETCH_ORI_REL,
Eg.
$result = $sth->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 671);
This is a part of the fetch function:
http://www.php.net/manual/en/pdostatement.fetch.php
But I don't see the need to do that, if you select the rows, you need it (all)...

PHP PDO mysql_data_seek

I'm converting some code to access a database to PDO. I've come across the following:
mysql_data_seek($result, 0);
$row0 = mysql_fetch_assoc($result);
And from my readings on Google etc, I understand this should be:
$row0 = $result->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, 0);
however this isn't working. Any ideas what i'm doing wrong?
From manual;
Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row.
You need a stmt that was created by PDO::prepare method.
Let's see this;
// assuming $pdo was created before as well
$sth = $pdo->prepare("SELECT name, colour FROM fruit");
// exec here
$sth->execute();
// get a row here
$row = $sth->fetch(PDO::FETCH_ASSOC);
// here probably you'll get a print out like
// Array([name] => Banana, [color] => Yellow)
print_r($row);
See more details here: PHP PDOStatement::fetch
First option with query:
You can iterate query result directly..
foreach ($db->query($sql) as $row) {
echo $row['FirstName'];
}
Second option with execute:
$sth = $db->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC); // fetch the next row from statement
echo $row['FirstName'];

Categories