Introduction
Connecting PHP to a MySQL database is one of the fundamental skills every PHP developer needs to master. In this tutorial, we'll walk through the process step by step.
Code for MySQL Connection with PHP
Here's the basic code for connecting PHP to MySQL using mysqli:
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'dbname');
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Step 1: Define the Hostname
In the code below, we define our hostname. For local development, you can use localhost. If you want to access another host, put that hostname or server IP here:
define('DB_SERVER', 'localhost');
Step 2: Define the Database Username
This code sets the database username. For local development, we typically use root. But you can create any database username you want:
define('DB_USER', 'root');
Step 3: Define the Database Password
Here we define the database password. For local development, you should leave it blank:
define('DB_PASS', '');
Step 4: Define the Database Name
Here we define our database name:
define('DB_NAME', 'dbname');
Step 5: Create the Connection
The mysqli_connect() function opens a new connection to the MySQL server:
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
Using PDO (Recommended)
For modern PHP applications, PDO (PHP Data Objects) is the recommended approach:
<?php
try {
$pdo = new PDO(
'mysql:host=localhost;dbname=mydb;charset=utf8mb4',
'root',
'',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
echo "Connected successfully!";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Best Practices
- Always use prepared statements to prevent SQL injection
- Store database credentials in environment variables, not in code
- Use PDO over mysqli for better portability
- Always handle connection errors gracefully
- Close connections when they're no longer needed
0 Comments
Leave a Comment