How to connect properly using mysqli
- Object syntax
- Credentials explained
- Functions explained
- Procedural syntax
- Handling connection errors
- Accessing the newly created connection
- Storing database credentials
- Include files
- Comments (6)
Having answered thousands questions on Stack Overflow, I was able to determine the most common problems PHP developers stuck into when working with mysqli. So I decided to write this tutorial emphasizing on the following matters:
- setting the proper character set for the connection will eliminate the whole class of errors, such as weird characters/question marks instead of your data, empty json_encode() output, problems with storing emojis, etc.
- besides, using exceptions will make the code drastically shorter, without the need to verify the every function for the failure manually
- setting the proper error reporting mode will eliminate the cryptic error messages like
mysqli_fetch_assoc() expects parameter.../Call to a member function bind_param()..., giving you the actual error message from MySQL instead. - security is not a laughing matter, there should be not a chance to leak your database details to the outside
Object syntax
$host = '127.0.0.1';
$port = 3306;
$dbname = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli($host, $user, $pass, $dbname, $port);
$db->set_charset($charset);
$db->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
unset($host, $dbname, $user, $pass, $charset, $port); // we don't need them anymore
Credentials explained
First of all we are defining variables that contain connection credentials. This set is familiar to anyone who were using the old mysql_connect() function, save for $charset may be, which was rarely used (although it should have been).
$hoststands for the database host. In case of the local development, it is most likely be127.0.0.1orlocalhost. In case of the live site, the actual hostname should be provided by the site admin / hosting provider. Note that connecting through IP address could save you a headache or two, so if you have a trouble with "localhost", try to use 127.0.0.1 instead.$dbnameis the name of the database in MySQL (the value that you were passing intomysql_select_db()). On your local server it could be anything, while on a live site again it should be given to you by the admin / provider.$user- a database user$pass- a database password$portis the port number on the database host that listens for connections. It is reported that some PHP dev environments such as MAMP are using non-default port number, so you have to check it out and change if necessary.$charsetis a very important option. It is telling the database in which encoding you are sending the data in and would like to get the data back. Note that due to initially limited support of Unicode in theutf8MySQL charset, it is now recommended to useutf8mb4instead.- the options() call tells mysqli to return the data in its native type, particularly ints and floats
Functions explained
Beside new mysqli() we are using two additional functions here:
- mysqli_report() is very important as it sets the proper error reporting mode for mysqli, telling it to throw an exception in case of error. Which is good in so many ways, which are explained in the article on PHP error reporting.
- mysqli::set_charset is the proper way to set the character set for the connection, as opposed to running the
SET NAMESquery.
Procedural syntax
Previously here was an example for the procedural mysqli syntax. But some time ago I decided to remove it for the following reasons:
-
procedural syntax is much more verbose than object syntax, just compare
$stmt->bind_param(..); // vs. mysqli_stmt_bind_param($stmt, ..); - object syntax is very simple. You don't have to learn OOP to use it. It's just a syntax which only slightly different from procedural. Just a simple rule: type a variable name, then an arrow and then a function name:
$stmt->bind_param()it is really simple. - most important of all: procedural syntax is deceptive in regard of error reporting. Even with error reporting properly set, procedural calls fail to report errors, ending up with cryptic error messages such as "invalid object or resource mysqli_stmt"
Just adapt the object syntax, it will take you just two minutes, but your code will start looking much cooler immediately!
Handling connection errors
An uncaught exception is converted to a PHP fatal error. It is not a problem by itself, errors are for the good. A programmer desperately needs an error message to get the idea on what's going on when something goes wrong. But such a converted error contains a stack trace added to the error message, which in case of mysqli connection error would include the constructor parameters, which happen to be the database credentials. Again, it shouldn't be a problem, as on a live site displaying errors should be always turned off anyway, but we are humans and we make mistakes. So, to avoid even a slight chance to reveal the credentials, we are catching the Exception and immediately throwing a brand new one with the same error message but without erasing the stack trace. Usually it's a bad move but in this case it's considered a good trade-off between security and convenience.
Just keep in mind that if your connection code is wrapped in a function, this function's parameters will be shown in the stack trace in turn. So, to avoid the credentials leak in this place, either send the credentials into this function in the form of an array or an object, or fetch them inside the function.
Accessing the newly created connection
There is one thing that makes mysqli a bit more complex to use than old mysql_connect related stuff. Although one was able to call mysql_query() anywhere in the code, without taking care of the connection, which was magically supplied by PHP, with mysqli one should always make sure that once created mysqli instance is available in each part of their script. In a nutshell, it's all about accessing a $db variable inside functions and object's methods.
So, to use mysqli in the global scope, just create a PHP file with the code above, and then include it in the every PHP script that needs a database connection. Whereas to access it in the functions/methods simply pass it as a parameter:
function getUserData($db, $id) {
$stmt = $db->prepare("SELECT * FROM user WHERE id=?");
$stmt->bind_param("s", $id);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
remember that if a function is called inside another function, this outer function should take the $db variable as a parameter as well.
In case your code is OOP, you most likely would put it in the constructor of your own database wrapper class. In this case you may want to check whether your class has any of the common mistakes, just in case.
Storing database credentials
Having credentials hardcoded in the same file quickly proves inconvenient. When the site goes live, it would need different credentials for sure, hence you would have to rewrite this file. And when you will need to work a bit more on the code, you will have to rewrite it back... and so on. Which is far from being convenient.
There are many advanced techniques for providing the settings but the simplest one would be just storing them in a separate file. This way you'll be able to keep different configuration files on different servers. So instead of hardcoding the credentials, just use variables defined in a separate file:
<?php
$host = '127.0.0.1';
$port = 3306;
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
and then just include this file in your database connection script
Include files
To sum everything up, let's create two files, one named mysqli.php with the following code inside,
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
require __DIR__.'/db_credentials.php';
$db = new mysqli($host, $user, $pass, $db, $port);
$db->set_charset($charset);
$db->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
unset($host, $db, $user, $pass, $charset);
function mysqli_info_array($mysqli) {
$pattern = '~Rows matched: (?<matched>\d+) Changed: (?<changed>\d+) Warnings: (?<warnings>\d+)~';
preg_match($pattern, $mysqli->info, $matches);
return array_filter($matches, "is_string", ARRAY_FILTER_USE_KEY);
}
and also in the same directory a file called db_credentials.php where the credentials should go.
Related articles:
- Mysqli tutorial (how to use it properly)
- How to report errors in mysqli
- Why mysqli prepared statemens are so hard to use?
- Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given.
- How to check whether a value exists in a database using mysqli prepared statements
- Mysqli helper function
- Authenticating a user using mysqli and password_verify()
- How to get the number rows that have been inserted, changed or skipped
- Mysqli's features you probably would like to know about
- Mysqli examples
- How to run INSERT query using Mysqli
- How to use mysqli properly
Comments:
Hello. As I build my 'much-improved' (thanks to your exceptional documentation) PHP code, I noticed that you do not 'unset' the $port variable. I assume this is an oversight but I wanted to make sure there wasn't some other reason. Thank you!
Reply:
Hello Neil!
Thank you very much for noticing that. I added $port recently and forgot to add it to unset. Fixed now!
Hello. Before I ask my question I must tell you how fortunate I am to have 'stumbled upon' your amazing resources. I wish I had found this two years ago when I started working on databases, this would've saved me hours and hours of grief. Thank you for such a thorough and comprehensive deep-dive into the world of mysqli.
Now for my question. I had read recently that it was advised to place a file containing credentials in a place 'above' the folder structure for the website to offer another layer of security. This requires a set_path in every file to point to the new location. In your documentation you state "in the same directory a file called db_credentials.php" which implies you are comfortable with credentials in the same directory. Is there any benefit to having the credentials placed in a hidden folder as described above? Thank you for any advice you can give this inspired learner.
Reply:
Hello Neil and thank you for the kind words!
This kind of response helps me to keep going.
Yes, I am comfortable with credentials in the same directory. As long as it's a PHP file, it won't reveal any information outside.
Speaking of this particular file, it has been put in the same directory just for the simplicity. In your project you can put the configuration file wherever you want.
Regarding "hidden folders", it's a common practice that all files that do not serve the client's request (mysqli.php included) are indeed stored in folders that are above the document root. Just for the convenience.
To sum it up, there is noting wrong in having the configuration file in the same directory. The location should be chosen based on the general structure of your application only.
The only important thing to remember, is when you start using a Version Control system such as GIT, the configuration file must be excluded from the repository. So it will never be revealed in the version controls and also will allow to have different configuration for the different servers.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); Beware of this line of code. Although this is one of the best ways to get the database connection you must not use it if your just creating a website and debugging at the same time. This line of code will give you 'This page isn't working. somewebsite.com is currently unable to handle this request. HTTP ERROR 500'. For those who use mysql query error check function you would not get the result of that error.
Reply:
Hello Saad!
You are simply confusing the error itelf and the way PHP displays them.
Of course, mysqli_report() will give you the full error information, you just need to tell PHP to display them. Just add the following line to your code while debugging it and you will have the error message instead of 500 error:
Forget about the previous silly question.
BTW, you've done a brilliant job.
In the include file, is it fair to assume that the three dots preceding the "...$params);" are not really meant to be there?
Does this part mean that
the mysqli_sql_exception gives the code as a string by default?
Reply:
Hello Sasa!
Thank you for the very good question.
It was a copy-paste from my PDO connection code, and for PDOException the code indeed could be a string.
But for mysqli it doesn't seem to be the case, so I removed the casting.