When should quotation marks be used in SQL queries to avoid syntax errors in PHP?

Quotation marks should be used in SQL queries within PHP when dealing with string values to avoid syntax errors. This is necessary because SQL queries require string values to be enclosed in single quotes. Failure to do so can result in syntax errors. To avoid this issue, always remember to properly enclose string values in single quotes within SQL queries in PHP.

// Example of using quotation marks in SQL queries to avoid syntax errors in PHP
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Example SQL query with string value enclosed in single quotes
$sql = "SELECT * FROM users WHERE username = 'John'";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Username: " . $row["username"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();