To connect to a MySQL database in PHP, you can use either the mysqli extension or PDO (PHP Data Objects). Below are examples of connecting to a MySQL database using both mysqli and PDO.
Here's an example of connecting to a MySQL database using mysqli :
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
Here's an example of connecting to a MySQL database using PDO:
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
It's good practice to close the database connection when you're done with it:
Using mysqli :
$conn->close();
Using PDO:
$conn = null;
Here's a complete example using mysqli to connect to a MySQL database, execute a query, and fetch results:
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();
Here's a complete example using PDO to connect to a MySQL database, execute a query, and fetch results:
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
try {
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// SQL query
$sql = "SELECT * FROM users";
$stmt = $conn->prepare($sql);
$stmt->execute();
// Fetch all rows
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Output data
foreach ($result as $row) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
} finally {
// Close connection
$conn = null;
}
These examples should help you get started with connecting to a MySQL database using PHP.