SELECT query with PDO
There are several ways to run a SELECT query using PDO, that differ mainly by the presence of parameters, type of parameters, and the result type. I will show examples for the every case so you can choose one that suits you best.
Just make sure you've got a properly configured PDO connection variable that needs in order to run SQL queries with PDO and to inform you of the possible errors.
SELECT query without parameters
If there are no variables going to be used in the query, we can use a conventional query() method instead of prepare and execute.
// select all users
$stmt = $pdo->query("SELECT * FROM users");
This will give us an $stmt object that can be used to fetch the actual rows.
Getting a single row
If a query is supposed to return just a single row, then you can just call fetch() method of the $stmt variable:
// getting the last registered user
$stmt = $pdo->query("SELECT * FROM users ORDER BY id DESC LIMIT 1");
$user = $stmt->fetch();
Note that in PHP you can "chain" method calls, calling a method of the returned object already, like:
$user = $pdo->query("SELECT * FROM users ORDER BY id DESC LIMIT 1")->fetch();
Selecting multiple rows
There are two ways to fetch multiple rows returned by a query. The most traditional way is to use the fetch() method within a while loop:
$stmt = $pdo->query("SELECT * FROM users");
while ($row = $stmt->fetch()) {
echo $row['name']."<br />\n";
}
This method could be recommended if rows have to be processed one by one. For example, if such processing is the only action that needs to be taken, or if the data needs to be pre-processed somehow before use.
But the most preferred way to fetch multiple rows which would to be shown on a web-page is calling the great helper method called fetchAll(). It will put all the rows returned by a query into a PHP array, that later can be used to output the data using a template (which is considered much better than echoing the data right during the fetch process). So the code would be
$data = $pdo->query("SELECT * FROM users")->fetchAll();
// and somewhere later:
foreach ($data as $row) {
echo $row['name']."<br />\n";
}
SELECT query with parameters
But most of time we have to use a variable or two in the query, and in such a case we should use a prepared statement (also called a parameterized query), first preparing a query with parameters (or placeholder marks) and then executing it, sending variables separately.
In PDO we can use both positional and named placeholders. For simple queries, personally I prefer positional placeholders, I find them less verbose, but it's entirely a matter of taste.
SELECT query with positional placeholders
// select a particular user by id
$stmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
$stmt->execute([$id]);
$user = $stmt->fetch();
SELECT query with named placeholders
// select a particular user by id
$stmt = $pdo->prepare("SELECT * FROM users WHERE id=:id");
$stmt->execute(['id' => $id]);
$user = $stmt->fetch();
Selecting multiple rows
Fetching multiple rows from a prepared query would be identical to that from a query without parameters already shown:
$stmt = $pdo->prepare("SELECT * FROM users LIMIT ?, ?");
$stmt->execute([$limit, $offset]);
while ($row = $stmt->fetch()) {
echo $row['name']."<br />\n";
}
or
$stmt = $pdo->prepare("SELECT * FROM users LIMIT :limit, :offset");
$stmt->execute(['limit' => $limit, 'offset' => $offset]);
$data = $stmt->fetchAll();
// and somewhere later:
foreach ($data as $row) {
echo $row['name']."<br />\n";
}Related articles:
- INSERT query using PDO
- UPDATE query using PDO
- How to connect to MySQL using PDO
- PDO Examples
- Authenticating a user using PDO and password_verify()
- How to check if email exists in the database?
- Select the number of rows using PDO
- How to create a WHERE clause for PDO dynamically
- DELETE query using PDO
- How to create a prepared statement for UPDATE query
- Getting a nested array when multiple rows are linked to a single entry
- How to execute 1000s INSERT/UPDATE queries with PDO?
- Adding a field name in the ORDER BY clause based on the user's choice
- INSERT helper function for PDO Mysql
- PDO Examples
- PDO Examples
Comments:
How do I add results from a query? array_sum won't work?
Reply:
You need to use prepared statements and ask your database to to the summing
I have 2 questions for you: (1) How can I find the autoincrement value of a primary key after the last INSERT (i.e. the value of the primary key index after an INSERT), and (2) How can I use a variable tablename in an INSERT. I've tried $tablename but it doesn't work
Reply:
Hello Adam!
To get the inserted Id you need PDO::lastInsertId(). See https://phpdelusions.net/pdo#affected
You cannot prepare a table name. So you have to put it directly in the query. You have to validate it first: https://phpdelusions.net/pdo_examples/order_by
This not working, no replacing vars limit and offset in query when execute:
Reply:
Hello Damian
In order to make it work, you need to turn the emulation off, as explained here https://phpdelusions.net/pdo#limit
Your tutorial on SELECT query with multiple parameters was very useful to me.
Would you please share a tutorial on Pdo multiple parameters pagination?
Many thanks in advance
Can you please do a write up on how to generate PHP code for a *.wsdl file that uses the WS-Security for authentication? There are many simple examples on consuming a web service in php usng a wsdl file but none of them involves security. Thank you.
Dear Sir, Thank you very much for the great help and your precious time. Indeed, I implemented the recommendation fully, as below:
The result?: You searched for: PHP Delusions Q1rows: [PHP Delusions] 0 row(s) found. Actually, the reason I used so many conditions in my prior code was to help me trap the source of the problem. Above code works perfectly in PHPMyAdmin. Please, give it another thought, maybe PHP, PDO settings, etc. relative to the Match()Against() construct.
Dear Sir, Please help me with this code! It is killing me! In my PHP, the $keywords variable comes in via my search field. It is wrapped in single ' '. I get 1 row. No wrapping, I get 1 row! I ran the code in MySql console successfully & got the 56 rows I expected from my db. Tried ? and :keywords Placeholders, I get 1 row! Did direct binding with both bindParam() and bindValue(), as PARAM_ STR & PARAM_INT respectively, same result, 1 row! Passed $keywords variable as array to execute() method, the same result! What now should I do to survive this, please, help. Also, the pg_desc field is indexed for fulltext search.
Reply:
Hello Ezeribe Adolf!
This issue is very simple. And it is actually a very common mistake. when you run a count(*) query, a database already counts the rectods for you, and therefore you shouldn't call the rowCount() method. Instead, you need to fetch the result.
And speaking of quotes, there should be NONE of them. I removed all the quotes from your code, as well as all the useless conditions:
Thanks for the excellent site and tutorials, hugely useful resource. I think there maybe a typo on the 2nd to last code snippet above, shouldn't it be $pdo->prepare in both cases rather than $pdo->query given you are passing parameters?
Reply:
Thank you!
You are absolutely correct, it must be prepare indeed! Fixed.
Thanks for the amazing tutorial. So, I'm having an issue. I trying to fetch posts from a WordPress database table "wp_posts", output the rows as json to be printed through Javascript (I'm using ajax to connect to the api). My code:
Even when I use "while" with the same "array_push($data, $posts)". I get nothing when I check for the response from the api request but if I "$out['data'] = var_dump($data) or var_export($data)", I get everything in the response. I don't know what I'm doing wrong.
Reply:
I am not sure but this is what you probably need
in case it's still nothing check the connection encoding ash shown in the connection example.
I am trying to select files with owner='xHswu' and format='mkv'. Here's my $sql:
I don't see in any of your examples in which the WHERE clause contains more than one field to check against. Or maybe I am doing something wrong there's is better way to achieve what I am trying to do. -Newbie
Reply:
Hello Dalton!
this is more an SQL related question because PDO only handles placeholders while the rest is just regular SQL. And yes, in SQL you need to use the AND keyword to make your query meed both criteria.
So just remove the second query and everything should work.
I Staff, it is possible something like :
as filter the TABLE_NAME ? always thanks
Reply:
Hello!
Nope it is not possible.
You must filter the table name manually.
I describe this approach here and here.
I'm trying to display a message when the query get no result from database. But it displaying error. This is my code:
I want to break a text into individual words and search every word that matches in the table. They do not need to be in order.
The execute array doesn't seem to work. Kindly help or any solution is much appreciated.
If we do this query, will it work slowly?
// $sql = ('SELECT FROM mother WHERE id = :id'); $stmt = $this->connect()->prepare('SELECT FROM mother WHERE id = :id'); $stmt->execute(['id' => $id]); while ($result = $stmt->fetch()){ $show[] = $result; return $show; } return $stmt; }
Please!! answer me!
Reply:
Hello Pink!
Nope, it will run fast.
The code is not optimal though. It should be just
Thanks for this fantastic tutorial. It is highly appreciated. While working with it, I ran into this challenge: PDOException: SQLSTATE[HY093]: Invalid parameter number in C:\new\private\search.php on line 68. Here is the code, most of it, please. Kindly help me with what I am doing wrong, please.
Reply:
Hello Ezeribe Adolf!
Just create a separate placeholder for each keyword, and bind the same variable multiple times for them
and it would work
Great help, Execellent and thnaks a lot.
Hello, the following code seems to be OK, but displaying the array with foreach won't work!
This yielded an ASSOC ARRAY $results.
It strikes me that it is an array within an array.
Anyway:
does not work, it does not display anything at all, although the (inner) array contains the desired filednamens (items) and values from the database as you can see. What do I wrong? Hope you have a solution
Reply:
Hello Gert.
Yes, fetchAll() returns you an array of arrays, it's the exact purpose of this function.
When you iterate over its results, you get another array which represents a row from the database. And what we are doing with arrays? Using foreach. So you have to add another foreach inside the first one.
Or you can echo distinct elements without foreach, as shown in the article above:
I hate to be an ass but your code nor anybody I have found code from works that includes php themsleves I think You need to give a proper tutorial not a piece meal of not working code again I know this may anger You but what angers me is when i go to find code and I get half the code and it does not work.
Not a single one of your examples work for selecting anything like you explain I can assure that as I know i'm trying it. for the past week
I wish to change to PDO for inline table edit. I want to use your update query method, but have not been able to transpose it yet. Any help would be great.
Reply:
Hello James!
That's a very good question.
Given you are updating just a single field, it would be easy to rewrite it to PDO
Note that $columns[$colIndex]'s value is hardcoded in your script and that's the very right thing you are supposed to do, this part is already safe!