How to Connect to MySQL in PHP: Simple Guide
To connect to MySQL in PHP, use the
mysqli extension by creating a new mysqli object with your database host, username, password, and database name. Check the connection for errors to ensure it is successful.Syntax
The basic syntax to connect to MySQL in PHP uses the mysqli class. You create a new instance with four parameters: host, username, password, and database name.
- host: The server address, usually
localhost. - username: Your MySQL username.
- password: Your MySQL password.
- database: The name of the database you want to use.
After creating the connection, check if it failed by inspecting the connect_error property.
php
$conn = new mysqli($host, $username, $password, $database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
Example
This example shows how to connect to a MySQL database named testdb on localhost with username root and no password. It prints a success message or an error.
php
<?php $host = "localhost"; $username = "root"; $password = ""; $database = "testdb"; $conn = new mysqli($host, $username, $password, $database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully to MySQL database."; ?>
Output
Connected successfully to MySQL database.
Common Pitfalls
Common mistakes when connecting to MySQL in PHP include:
- Using wrong credentials (host, username, password, or database name).
- Not checking for connection errors, which can cause silent failures.
- Forgetting to close the connection after use (optional but recommended).
- Using deprecated
mysql_connect()instead ofmysqlior PDO.
php
<?php // Wrong way: no error check $conn = new mysqli("localhost", "root", "", "wrongdb"); // This may cause errors later without notice // Right way: check connection $conn = new mysqli("localhost", "root", "", "wrongdb"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
Quick Reference
Remember these tips when connecting to MySQL in PHP:
- Use
mysqlior PDO for modern, secure connections. - Always check
$conn->connect_errorafter connecting. - Use
localhostas host if your database is on the same server. - Close the connection with
$conn->close();when done.
Key Takeaways
Use the mysqli class with host, username, password, and database to connect to MySQL in PHP.
Always check for connection errors using the connect_error property.
Avoid deprecated mysql_connect; prefer mysqli or PDO for database connections.
Use localhost as host if your database runs on the same machine as PHP.
Close your database connection after finishing queries to free resources.