Search code examples
phppdo

Uncaught PDOException: Syntax error or access violation: You have an error in your SQL syntax


I'm struggling trying to query a database inside of a PHP class. I'm getting an error when trying to echo out the email address. I'm new to classes and can't seem to get this to work but if I do a normal PHP function, it works fine.

// using composer autoload.php

$user = new User($pdo);
$email = $user->getEmail($username);
echo $email

$pdo comes from database.php which connects to the MariaDB database.

Below is the class file:

class User
{
    private $dbc;

    public function __construct(\PDO $pdo)
    {
        $this->dbc = $pdo;
    }

    public function getEmail($username)
    {
       $stmt = $this->dbc->query('SELECT * FROM users WHERE username=?');
       $stmt->execute([$username]);
       $request = $stmt->fetch();
       return $request['email'];
    }
}

Solution

  • Try changing this: $stmt = $this->dbc->query('SELECT * FROM users WHERE username=?'); to $stmt = $this->dbc->prepare('SELECT * FROM users WHERE username=?'); which prepare the statement with placeholders for the values that will be bound later.