How can the use of single quotes in PHP variables impact the execution of MySQL queries?

When using single quotes in PHP variables within MySQL queries, it can cause syntax errors or unexpected behavior because single quotes are used to delimit string values in SQL. To avoid this issue, you should use prepared statements or escape the variables properly using functions like mysqli_real_escape_string() to prevent SQL injection attacks.

// Example of using prepared statements to avoid SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = "example'; DROP TABLE users; --";

$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // Process the results
}

$stmt->close();
$mysqli->close();