PHP Connect to MySQL

Connecting to a MySQL database using PHP involves establishing a connection with the MySQL server and selecting the appropriate database to work with. Here’s an example of how to connect to a MySQL database using PHP:

<?php
// MySQL server configuration
$servername = "localhost";
$username = "root";
$password = "";
// Create a connection
$conn = mysqli_connect($servername, $username, $password);
// Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
// Select the database
$dbname = "mydatabase";
mysqli_select_db($conn, $dbname);
echo "Connected successfully to database " . $dbname;
// Close the connection
mysqli_close($conn);
?>

n this example, we first define the configuration for the MySQL server by specifying the server name, username, and password. We then create a connection to the server using the mysqli_connect() function and store the connection in a variable called $conn. We check if the connection was successful using the mysqli_connect_error() function and terminate the script if there was an error.

Next, we select the database we want to work with by specifying its name in the $dbname variable and using the mysqli_select_db() function to select it. We then print a message to indicate that we have successfully connected to the database.

Finally, we close the connection using the mysqli_close() function.