MySQL is a widely used, open-source relational database management system. PHP and MySQL make a powerful combination for web development, allowing you to create dynamic and data-driven applications. In this lesson, we'll explore how to interact with MySQL databases using PHP, including establishing connections, querying data, and handling results.
To connect to a MySQL database, you can use the mysqli
or PDO
extension in PHP. In this lesson, we'll use the mysqli
extension.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
$sql = "SELECT id, firstname, lastname FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$sql = "INSERT INTO users (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "UPDATE users SET email='[email protected]' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$sql = "DELETE FROM users WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
Practice interacting with a MySQL database using PHP by completing the following exercises: