Connecting to a MySQL database is important for web developers who need to store or retrieve data from a database. In this tutorial, you’ll learn how to connect to a MySQL database using PHP.
Step 1: Install MySQL
Before you can connect to a MySQL database, you’ll need to have MySQL installed on your computer or server. If you haven’t already installed MySQL, you can download it from the official MySQL website.
Step 2: Create a database and table
Once you have MySQL installed, you’ll need to create a database and table to store your data. You can use the MySQL command line interface or a tool like phpMyAdmin to create your database and table.
Creating a database using the MySQL command line interface:
1 2 |
mysql -u username -p CREATE DATABASE dbname; |
Creating a table using phpMyAdmin:
- Log in to phpMyAdmin.
- Select the database that you want to create the table.
- Click on the “Create table” button.
- Enter the table name and the number of columns you want.
- Click on the “Go” button to create the table.
Step 3: Connect to the database using PHP
To connect to a MySQL database using PHP, you’ll need to use the mysqli_connect()
function. Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "dbname"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; |
Step 4: Close the database connection
After you’re done using the database, you should close the database connection using the mysqli_close()
function.
1 2 |
// Close connection mysqli_close($conn); |
That’s it! You now know how to connect to a MySQL database using PHP. Feel free to explore more about mysqli functions.
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "dbname"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; // Close connection mysqli_close($conn); |