Skip to content
PHP Logo

What potential pitfalls should be considered when trying to output data from a MySQL database using PHP in a forum environment?

One potential pitfall when outputting data from a MySQL database in a forum environment is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, use prepared statements with parameterized queries to securely interact with the database.

php
// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "forum";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Prepare and execute a parameterized query
$stmt = $conn->prepare("SELECT * FROM posts WHERE id = ?");
$stmt->bind_param("i", $post_id);

// Set parameter values
$post_id = 1;

// Execute query
$stmt->execute();

// Process results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Output data from database
    echo $row['title'];
    echo $row['content'];
}

// Close statement and connection
$stmt->close();
$conn->close();