What are some common pitfalls when using PHP scripts to interact with a MySQL database?

One common pitfall when using PHP scripts to interact with a MySQL database is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to safely execute SQL commands.

// Example of using prepared statements to interact with MySQL database

// Establish connection to 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);
}

// Prepare a SQL query using a prepared statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set parameter values and execute the query
$username = "example_username";
$stmt->execute();

// Bind the result to variables
$stmt->bind_result($id, $username, $email);

// Fetch and display the results
while ($stmt->fetch()) {
    echo "ID: " . $id . " - Username: " . $username . " - Email: " . $email . "<br>";
}

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