The last article explained how to create a To-Do List app with PHP and SQL. We will now explore how to connect PHP to a database, a crucial step in website development, allowing scripts to access stored data. This guide will show you how to connect PHP to a MySQL database.
Step 1: Database Configuration
Before we begin, ensure that you have a MySQL database set up. You’ll need to have the following information on hand:
- Hostname- The username or IP address of the MySQL server.
- Username- The login username for the MySQL server.
- Password- The password for accessing the MySQL server.
- Database Name- The name of the MySQL database you wish to connect to.
Step 2: Establishing the Connection
Next, we will develop a PHP script to set up a link to the MySQL database. We will utilize the mysqli extension, which offers a structured approach to communicate with MySQL databases. create a file db.php and insert the given code.
<?php
// Database configuration
$host = 'localhost'; // Hostname
$username = 'your_username'; // Username
$password = 'your_password'; // Password
$database = 'your_database'; // Database name
// Establish a connection to the database
$conn = new mysqli($host, $username, $password, $database);
// Check for connection errors
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
// Connection successful
echo 'Connected to the database successfully';
?>
Step 3: Testing the Connection
In order to check the connection, just add the db.php file to any PHP script that requires communication with the database. For instance:
<?php
// Include the database configuration file
require_once 'db.php';
// Your PHP code here
?>
If the script runs successfully, the browser will show the message “Connected to the database successfully.” Any connection errors will be shown if they occur.
Step 4: Closing the Connection (Optional)
Although PHP automatically closes the database connection after executing the script, it is recommended to manually close the connection using the close() method on the database connection object when finished.
<?php
// Close the database connection
$conn->close();
?>
Conclusion
Great Job! You have mastered the skill of linking PHP to a MySQL database. It is crucial to connect to the database to engage with the stored data effectively. Always prioritize the secure storage of your database login details and remember to close the connection when it’s not in use. Enjoy coding!