How can PHP interact with a database, such as MySQL, to store and retrieve reservation information?
To interact with a MySQL database in PHP to store and retrieve reservation information, you can use the MySQLi or PDO extension. These extensions allow you to establish a connection to the database, execute SQL queries to insert or retrieve data, and handle errors gracefully.
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert reservation information into the database
$sql = "INSERT INTO reservations (name, date, time) VALUES ('John Doe', '2022-12-31', '18:00')";
if ($conn->query($sql) === TRUE) {
echo "Reservation successfully added";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Retrieve reservation information from the database
$sql = "SELECT * FROM reservations";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Date: " . $row["date"]. " - Time: " . $row["time"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();