Connecting to a MySQL database using PHP is a common task for web developers. The connection process involves several steps: setting up the MySQL server, creating a database and a user, and then writing PHP code to establish the connection.
Here’s a step-by-step guide:
Step 1: Set Up MySQL Server
Before you can connect to a MySQL database, you need to have MySQL installed and running on your server. You can download and install MySQL from the official MySQL website.
Step 2: Create a Database and User
Log in to your MySQL server and create a database and a user with appropriate privileges. This can be done using the MySQL command line or a tool like phpMyAdmin.
Using MySQL Command Line
— Log in to MySQL server as root
mysql -u root -p
— Create a new database
CREATE DATABASE my_database;
— Create a new user and grant privileges
CREATE USER ‘my_user’@’localhost’ IDENTIFIED BY ‘my_password’;
GRANT ALL PRIVILEGES ON my_database.* TO ‘my_user’@’localhost’;
FLUSH PRIVILEGES;
— Exit MySQL
EXIT;
Step 3: Write PHP Code to Connect to MySQL Using Procedural Method
Here’s how you can connect to a MySQL database using the procedural method with mysqli:
<?php
$servername = “localhost”;
$username = “my_user”;
$password = “my_password”;
$database = “my_database”;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
echo “Connected successfully”;
// Close the connection
mysqli_close($conn);
?>
Explanation of the Code
- Connection Parameters:
- $servername: The hostname of the MySQL server. For local development, this is usually localhost.
- $username: The username to connect to the MySQL database.
- $password: The password for the MySQL user.
- $database: The name of the database you want to connect to.
- mysqli_connect:
- This function is used to open a new connection to the MySQL server.
- It takes four parameters: the server name, the username, the password, and the database name.
- mysqli_connect_error:
- This function returns a string description of the last connect error, if any.
- mysqli_close:
- This function closes the previously opened database connection.