Mysqli SELECT query with prepared statements
- SELECT query with prepared statements
- Detailed explanation
- Getting multiple rows into array
- SELECT query with a helper function
- Comments (15)
Before running any query with mysqli, make sure you've got a properly configured mysqli connection variable that is required in order to run SQL queries and to inform you of the possible errors.
SELECT query with prepared statements
You must always use prepared statements for any SQL query that would contain a PHP variable. To do so, always follow the below steps:
- Create a correct SQL SELECT statement. Test it in mysql console/phpmyadmin if needed
- Replace all variables in the query with question marks (called placeholders or parameters)
- Prepare the resulting query
- Bind all variables to the previously prepared statement
- Execute the statement
- Get the mysqli result variable from the statement.
- Fetch your data
Long story short, here is the code:
$sql = "SELECT * FROM users WHERE id=?"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$user = $result->fetch_assoc(); // fetch data
Starting from PHP 8.2 you can do it all in one line:
$sql = "SELECT * FROM users WHERE id=?";
$user = $conn->execute_query($sql, [$id])->fetch_assoc();
And have your SELECT query executed without a single syntax error or SQL injection.
Detailed explanation
Let's see what does every line of this code mean
$sql = "SELECT * FROM users WHERE id=?";
Like it was said above, first we are writing an SQL query where all variables are substituted with question marks.
IMPORTANT! there should be no quotes around question marks, you are adding placeholders, not strings.
$stmt= $conn->prepare($sql);
Then, the query is prepared. The idea is very smart. To avoid even a possibility of the SQL injection or a syntax error caused by the input data, the query and the data are sent to database server separately. So it goes on here: with prepare() we are sending the query to the database server ahead. A special variable, a statement is created as a result. We would use this variable from now on.
$stmt->bind_param("i", $id);
Then variables must be bound to the statement. The call consists of two parts - the string with types and the list of variables. With mysqli, you have to designate the type for each bound variable. It is represented by a single letter in the first parameter. The number of letters should be always equal to the number of variables. The possible types are
- i for integer
- d for double (float)
- s for string
- b for blobs
A HINT: you can almost always safely use "s" for any variable.
So now you can tell that "s" means "there would be 1 variable, of string type".
$stmt->execute();
Then the query finally gets executed. Means variables get sent to the database server and the query is actually executed.
NOTE that you don't have to check the execution result. Given you have the proper connection code mentioned above, in case of error mysqli will raise an error automatically.
$result = $stmt->get_result(); // get the mysqli result
Here we are calling a very smart function. By default, for some reason it's impossible to fetch a familiar array (like we did with mysql_fetch_array()) from a mysqli statement. So this function is here to help, getting a mysqli result from a mysqli statement.
$user = $result->fetch_assoc(); // fetch data
Finally, fetching a row using a familiar fetch_assoc() method.
Getting multiple rows into array
Generally, getting multiple rows would involve a familiar while loop:
$sql = "SELECT * FROM users WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['name'];
}
However, in a modern web-application the database interaction is separated from the HTML output. It makes the code much cleaner and more flexible. It means that we should never print our data using a while loop but rather collect it into array and then use this array for the output.
And mysqli has a handy function that instantly returns an array from the query result: mysqli_fetch_all(). So instead of four lines
$data = [];
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
it could be just a single line:
$data = $result->fetch_all(MYSQLI_ASSOC);
after which you can use the $data for the output:
<?php if ($data): ?>
<ul>
<?php foreach($data as $row): ?>
<li><?= $row['name'] ?></li>
<?php endforeach ?>
</ul>
<?php else: ?>
No data found
<?php endif ?>
By default this function returns enumerated arrays, so to get associative arrays the MYSQLI_ASSOC mode must be set explicitly.
SELECT query with a helper function
As you may noted, the code for a prepared statement is quite verbose. If you like to build a code like a Lego figure, with shining ranks of operators, you may keep it as is. If you, like me, hate useless repetitions and like to write concise and meaningful code, then there is a simple helper function. With it, the code will become two times shorter:
$sql = "SELECT * FROM users WHERE id=?"; // SQL with parameters
$stmt = prepared_query($conn, $sql, [$id]);
$user = $stmt->get_result()->fetch_assoc(); // fetch a row
// or
$users = $stmt->get_result()->fetch_all(MYSQLI_ASSOC); // fetch an array of rows
Only three lines instead of six!
Related articles:
- How to run an INSERT query using Mysqli
- How to run a SELECT query using Mysqli
- How to run an UPDATE query using Mysqli
- Mysqli prepared statement with multiple values for IN clause
- Using mysqli prepared statements with LIKE operator in SQL
- How to create a search filter for mysqli
- Mysqli examples
- How to call stored procedures with mysqli
- How to run 1000s insert queries with mysqli?
Comments:
can you please explain / show an example: 1 num_rows with a prepared select 2 affected_rows with a prepared insert thnks,
there is this query in procedural mysql, where u can compare two columns of the same rows. a am trying to exploit same in msqli prepared statement but could not figure out a way, please i need help. the query example is below. mysql> select * from table1 where column1 not in (select column2 from table1);
Hi there. Love this function! Use it all the time :)
I just want to know, how do I check for when a query doesn't work or there is an error? With $conn->query() you can check the variable $conn->error.
This doesn't produce an error when the query doesn't work:
Reply:
Hello Christie!
Glad you like this function. I use it all the time myself.
This $conn->error stuff is extremely dated and wrong in many ways. With modern PHP you don't need anything like that. Once mysqli is configured properly (you can see it here https://phpdelusions.net/mysqli ), the error will reveal itself, without $conn->error or anything. So you can write echo 'saved'; right away, without any conditions. In case of error it won't be shown, but the error instead. Simpler, more convenient, safer. That's how the modern programming is intended to work.
Recently I wrote an answer to a similar question on Stack Overflow, you may want to check the more detailed reasoning there: https://stackoverflow.com/a/74884566/285587
This answer is based on the general principles of error reporting that you are also welcome to read: https://phpdelusions.net/basic_principles_of_web_programming#error_reporting
I robot
ERROR: Trying to access array offset on value of type bool
where could be the problem with my code?
Reply:
Hello mathew
the problem is you are NOT using prepared statements properly. Please see examples on this page and actually follow them
Hello. How do we use prepared statements, in sql queries with more than one variable? Thanks.
very nice and very helpfull
Firstly thanks for the site! As a PHP newbie its great to have code samples. I'm trying to do something which should be simple.
works as I expect it to but
returns 0 results. What am I doing wrong?
Reply:
Hello Simon
Nothing wrong with the code you posted here.
Probably something wrong with the way you are telling that this query returned no rows.
caught Error: Call to undefined method mysqli_stmt::get_result(). I am getting this error while executing the query. Please help me
Reply:
Hello Rizwan!
You need to enable mysqlnd in the control panel of your hosting account
Hello. I have a function to display a data. Your help is much appreciated. Thanks.
Very nice article, It really help me. Thanks
Got your reply, thanks! But I keep getting a 500 internal server error on this exact code (when I remove it, the script works):
Any ideas?
Cool tut! Thanks! Quick question: I'm trying to retrieve data from a mysql DB based on the existence of a code. I used this:
I want to fill the vars $name2 and $mail from the DB. Is this the correct syntax? Thanks!
Reply:
Hello zoldos!
Yes you made it almost right, but for the assignment part, it works the opposite:
It's like in your math class, X =
Y * 2the result is in on the left.Besides, given you are fetching only one row, no while loop is needed. Also, closing the statement is not really needed.
Hence the correct code would be
Nice article! You have only one problem: in section "Getting multiple rows into array" in while loop it is while ($row = $result->fetch_assoc()) not while ($row = $stmt->fetch_assoc()).
Reply:
Hello!
Oh, thank you for spotting this mistake! Fixed!
Thank you! This is exactly what I was looking for. Examples I can use to better grasp the concepts! I shall be finishing my project with ease now. Well, it will be easier! Great writing, great tips, but one typo. I wouldn't normally mention such a thing, but it was in a line of code:
Reply:
Hello John!
Thank you very much for for the kind words and for catching this typo. Fixed on the spot! :)
Don't hesitate to ask any questions, it will help me to make the explanations better.