How do I connect a php script to a mysql database?

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:

  1. Create a database and a user in MySQL.
  2. Get the database connection details: hostname, username, password, and database name.
  3. 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";
?>

  1. 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).

Leave a Comment