Secure Guestbook: Modern PHP Database Interaction
Description
This snippet showcases a modernized guestbook application, improving upon an outdated, vulnerable legacy system. The original code suffered from significant security risks and performance limitations.
Original Code (Outdated)
```php
<?php
$db = mysql_connect('localhost', 'user', 'password');
mysql_select_db('guestbook', $db);
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$comment = $_POST['comment'];
mysql_query("INSERT INTO guestbook (name, comment) VALUES ('$name', '$comment')");
}
$result = mysql_query('SELECT * FROM guestbook');
while ($row = mysql_fetch_assoc($result)) {
echo "Name: " . $row['name'] . "<br>Comment: " . $row['comment'] . "<br><br>";
}
?>
```
Updated Code (Modern)
```php
<?php
// Database credentials
$host = 'localhost';
$username = 'user';
$password = 'password';
$dbname = 'guestbook';
// Create a new mysqli object
try {
$conn = new mysqli($host, $username, $password, $dbname);
} catch (mysqli_sql_exception $e) {
die('Error connecting to database: ' . $e->getMessage());
}
// Check for POST submission
if (isset($_POST['submit'])) {
// Sanitize user inputs
$name = $conn->real_escape_string($_POST['name']);
$comment = $conn->real_escape_string($_POST['comment']);
// Prepare and execute the INSERT query
$stmt = $conn->prepare("INSERT INTO guestbook (name, comment) VALUES (?, ?)");
$stmt->bind_param('ss', $name, $comment);
if ($stmt->execute()) {
echo 'Comment added successfully!';
} else {
echo 'Error adding comment: ' . $stmt->error;
}
$stmt->close();
}
// Select guestbook entries
$sql = 'SELECT name, comment FROM guestbook';
$result = $conn->query($sql);
if ($result) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . htmlspecialchars($row['name']) . "<br>";
echo "Comment: " . nl2br(htmlspecialchars($row['comment'])) . "<br><br>";
}
$result->free_result();
} else {
echo 'Error fetching comments: ' . $conn->error;
}
$conn->close();
?>
```