PHP Connect to MySQL

When PHP wants to work with a MySQL database, the first thing it has to do is connect to the database server. No connection, no queries, no inserts, no selects, nothing.

In PHP, the two main ways to work with MySQL are MySQLi and PDO. MySQLi is built specifically for MySQL. PDO is a more general database layer, so it can work with MySQL but also with other database systems. That means PDO gives you more flexibility if a project ever needs to switch databases later, while MySQLi is more tied to the MySQL world.

Both are perfectly valid. Both support prepared statements, which matter a lot because they help protect your application from SQL injection. That becomes a very important topic once you start accepting user input and sending values into queries.

MySQLi can be written in two styles: object-oriented and procedural. PDO is object-oriented. Since you just finished an OOP track, the object-oriented style is the cleaner one to focus on first. It will feel more consistent with what you have already been practicing.

To open a connection, PHP usually needs four pieces of information: the host, the username, the password, and the database name. Once you provide those, PHP tries to open the connection. If it succeeds, your script can continue. If it fails, you need to handle that failure clearly.

The MySQLi style usually checks the connection by looking for an error on the connection object. PDO often handles failures with exceptions, which means you wrap the connection attempt in try/catch. The practical idea is the same in both cases: try to connect, and if something goes wrong, do not blindly continue.

Closing the connection is simple too. In small practice scripts, it usually closes automatically when the script ends, but you can also close it manually. With MySQLi, you call the close method. With PDO, you usually set the connection variable to null.

So the real takeaway here is not memorizing three nearly identical examples. It is understanding the sequence: gather the connection details, open the connection, confirm it worked, and only then move on to actual database work.