To establish a connection between MySQL and PHP, you can use the MySQLi (MySQL Improved) extension or the PDO (PHP Data Objects) extension.
Both options provide a set of functions and methods to interact with MySQL databases.
Using MySQLi:
<?php
// Database credentials
$servername = "your_mysql_server";
$username = "your_mysql_username";
$password = "your_mysql_password";
$database = "your_mysql_database";
// Create a connection
$conn = new mysqli($servername, $username, $password, $database);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Perform database operations here
// Close the connection
$conn->close();
?>
Using PDO:
<?php
// Database credentials
$servername = "your_mysql_server";
$username = "your_mysql_username";
$password = "your_mysql_password";
$database = "your_mysql_database";
// Create a connection
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
// Perform database operations here
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// Close the connection (PDO automatically closes the connection when the script ends)
?>
Replace "your_mysql_server", "your_mysql_username", "your_mysql_password", and "your_mysql_database" with your actual MySQL server details.