Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading