How to connect to MySQL using PDO
- Example
- Credentials explained
- Connection options explained
- Handling errors
- Creating the connection
- Don'ts
- Accessing the newly created connection
- Comments (16)
In this example we will learn how to properly connect to Mysql database using PDO. It is based on the information provided in the main article on PDO but with additional explanations.
Surprisingly, there is no single state-of-the-art connection example in the PHP manual. Instead, different connection options are discussed in different chapters, which makes it hard for the learner to get a single robust example that is ready to use. Below you will find such an example, as well as the explanation of all the options used.
Example
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$port = "3306";
$charset = 'utf8mb4';
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset;port=$port";
$pdo = new \PDO($dsn, $user, $pass, $options);
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.$dbis 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$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.
Note it's a good idea to store connection variables (
$host, $dbetc.) in a separate file. This way you'll be able to have two versions of your code, one for the local server and one for the remote.
Connection options explained
Next we are creating an array with PDO options that are either critically important or just make your experience with PDO much better.
PDO::ATTR_ERRMODE- this is a cornerstone option that should be always set toPDO::ERRMODE_EXCEPTION. It tells PDO to throw an exception every time a query failed, so you won't have to get the error manually after every query call as it was used to be withmysql_query()PDO::ATTR_EMULATE_PREPARES- this option tell PDO whether to use an emulation mode or not. It is agreed upon that in general it's better to turn it off, however in some cases it is convenient to have it turned on. Luckily, this setting could be changed in runtime usingPDO::setAttribute()method, so let's make it turned off by default as a connection option, with the possibility to fall back later.PDO::ATTR_DEFAULT_FETCH_MODE- this option is used simply for convenience. Although the fetch method can be always set right in the fetch function call (like$row = $stmt->fetch(PDO::FETCH_ASSOC);), it is convenient to set it once for all and then just omit it in particular fetches. Besides, when iterating over a statement using foreach there is no place where we can set the fetch mode, so again it is convenient to set it beforehand. The two most popular fetch modes arePDO::FETCH_ASSOCandPDO::FETCH_OBJwhich make PDO to fetch the resulting row as an associative array or as an object.
Handling errors
A database module shouldn't report errors on its own, but should rely on the site-wide error handler. So there must be no error reporting code. For more details refer to the article.
Creating the connection
Having all the options and credentials set, we can finally proceed to creating a connection. To do so we need to create an instance of PDO class for which we need to supply 4 parameters of which the first one, called "DSN" being most important.
DSN is a semicolon-delimited string, consists of param=value pairs, that begins from the driver name and a colon:
mysql:host=localhost;dbname=test;port=3306;charset=utf8
driver^ ^ colon ^param=value pair ^semicolon
Note that it's important to follow the proper format - no spaces or quotes or other decorations have to be used in DSN, but only parameters, values and delimiters, as shown in the manual.
Beside DSN, we are using $user, $pass and $options variables defined above.
Don'ts
Beside things that you should do, there are always things that you should do not. Some of them we will discuss below.
PDO::ATTR_PERSISTENT. Although this option is rather popular in the copy-pasted cargo cult PDO examples, a learner should always avoid it. There are too many drawbacks (that are outside of the scope of this article) whereas no advantages for a small site at all. This option should be used after a strong consideration only, and by no means as a blindly copy-pasted option just in case.- using
die(),echoor any other output operator for the caught exception. As it is explained in the relevant article, PHP error reporting, an error message should never be printed unconditionally, but only according to the site-wide settings. And this should be done in the site-wide handler only.
Accessing the newly created connection
- Put the code above in a distinct file, called, for example,
pdo.php. - Include (using
require 'pdo.php';) this file into other files that require the database connection. - Use the
$pdovariable to access the PDO object. -
To use PDO inside functions, you must provide the PDO object as a parameter. For example:
function getUserData($pdo, $id) { $stmt = $pdo->prepare("SELECT * FROM user WHERE id=?"); $stmt->execute([$id]); return $stmt->fetch(); }
Related articles:
- SELECT query with PDO
- INSERT query using PDO
- UPDATE query 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:
'exlained'?
Reply:
OMG, I can't believe nobody noticed it for years (me included!).
Thank you, fixed!
You state in Creating the Connection:
I don't see the try/catch. Is it no longer necessary or an unintentional omission?
Reply:
Oh thank you! Yes, it is no longer necessary as PHP will take care of that risk, hiding password from the stack trace automatically, hence this ugly code has been removed from the example but I forgot to remove from text. Removing now.
may you share for me or explain how to submit user data from a form to the database in PDO
I came across your mydatabase for download and now i cannot find it... Can you point me to the URL.. is it free or paid usage.. Thanks
A suggestion: complete working examples would be nice. You clearly know and care about the content, but for users with less depth it's hard to string together the code snippets,. In other words I cant make use of most of the code here! You make points with code but I cant use any of it or learn as I can't take anything from here and experiment! It would take more room on the page, but placing each (or some) of the teaching into complete working code would help!
Thanks very much for this information. I have been a fan to this website ever since I discovered it. This is now my reference as concern PDO, I am presently creating a course/tutorial on PDO, this site is going to be my reference/source. That means, you would expect huge traffic when I will launch the course/tutorials
This is really a site to be reference. best regard Lynn
On line 5 missing ; at the end.
Reply:
Hello Oliver!
Thank you very much, fixed!
What is he best coding to use two queries on one page? One connection and then close it and do the connection over again for the second query? TIA
Reply:
Hello Jack!
The connection has to be opened only once!
Open it at the top of the page (better include a file with the connection code), and then run as many queries as you wish using the same connection.
can you please explain the working and use of below statements PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
Reply:
Hello akshaya!
That's an outdated method for setting the connection charset that was used 10 years ago. Nowadays it has to be done differently:
typo on the second header , missing p from example
Hello and thank you for your dedication to help others. I am new to PHP and a stickler for best practices. Your work here is excellent. I am building a large database site and want to know what is the ideal PDO connection script that is ultra safe and can be used repeatedly throughout the site.
Reply:
Hello Conrad!
Thank you for the kind words and a good question.
For the connection itself, the provided code is enough. Just put it in a php.file and include it (or rather require_once) in any script that needs a connection. Make sure that display_errors on a live server is set to 0, otherwise this code will print the database credentials out in case of a connection error.
As of the repeated use, it depends on how much functions and classes you are going to use and what is your coding style in general. For the old-style procedural scripts that don't use functions or classes this code is enough. If you are going to use functions, make sure that you are passing the PDO connection as a parameter for a function that needs it. If you are going to use OOP, make sure that you are passing the PDO connection as a constructor parameter for a class that needs it.
I am sure you could have other questions, don't hesitate to ask if so.
Hello, I am curious how you would test your connection? Is this an appropriate time for try/catch?
Reply:
Hello!
That's a very good question! The answer depends on what you are planning to do in case of connection error, or, to put it closer to your question, what code you want to put inside that catch block. If nothing particular, then it's no use for the try catch at all, because basic error reporting should be already good with connection errors as well.
There is an article on the error reporting, https://phpdelusions.net/articles/error_reporting I hope you will find it useful
Feel free to ask if you have other questions!
I include my database connection file and this works:
return ($result == 1); }
But I am not sure whether what you are saying amounts to the same thing. I mean it works, Im just trying to understand why when in my head it doesnt quite equal what you are saying!
Hi, I tried to do the nasty global approach but I found i dont need to add global $pdo to functions in a file where I include the database connection from another file. Just $pdo seems to be ok...
Reply:
Hello Ed!
If you need to access a variable inside a function,m you have to either pass it as a function parameter (i.e.
$var = func($pdo);) or declare it global inside.Why is the charset specified? Isn't the character set defined for the fields in the database definition? What if these two values conflict?
Reply:
Hello Justin!
That's a very good question!
Actually, a database has the ability to recode your data on the fly. And for this very reason you have to specify the charset. For example, it could be utf8 in the database but Windows-1252 on your page (well, you seldom could find such a page nowadays but still). In such a case you have to set a connection charset as cp1252, and then a database will recode your data from 1252 to utf and back.
There is also one more reason connected to the string literals added to the query directly or via emulated placeholders. Escaping rules are different for the different encodings and therefore it is important to specify the charset to let an escaping function to escept the data properly.
I love your explanation about pdo, I am new to pdo and will love to work with it in a project. Do you have any tutorial video that explains pdo in crud using oop method. Thanks for your time.