Skip to content
PHP Logo

How can SQL syntax errors be avoided when querying a database in PHP?

To avoid SQL syntax errors when querying a database in PHP, it is important to use prepared statements with parameterized queries. This helps prevent SQL injection attacks and ensures that the SQL syntax is correct.

php
// Establish a database connection
$connection = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement with a parameterized query
$statement = $connection->prepare("SELECT * FROM users WHERE id = :id");

// Bind the parameter value
$statement->bindParam(':id', $userId, PDO::PARAM_INT);

// Execute the statement
$statement->execute();

// Fetch the results
$results = $statement->fetchAll(PDO::FETCH_ASSOC);

// Loop through the results
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}