This article describes how to connect a PHP script to a MySQL database.
Here are the steps to connect a PHP script to a MySQL database:
- Create a database and a user in MySQL.
- Get the database connection details: hostname, username, password, and database name.
- Use the
mysqli
extension in PHP to connect to the MySQL database. Here is an example:
<?php
$host = "hostname";
$username = "database_username";
$password = "database_password";
$database = "database_name";
// Create a connection
$conn = mysqli_connect($host, $username, $password, $database);
// Check the connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
- Once you have a successful connection to the database, you can use the
$conn
variable to execute SQL queries and interact with the database.
Note: Always remember to close the connection after you’re done using it, using mysqli_close($conn)
.