dchhitarka
dchhitarka

Reputation: 31

Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation

I don't know why am I gettng the error

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Preprocessor' at line 1 in /var/www/html/phpquiz/result.php:17

There error occurs when executing the prepared statement i.e. on executing $cho->execute();

<?php
session_start();
if(!isset($_SESSION['score'])){
    $_SESSION['score'] = 0;
}

if(isset($_POST['submit'])){
    $arr = array("a", "b", "c", "d", "e");
    for($i = 1; $i < 6; $i++){
        $text = $_POST['que_'.$arr[$i-1]];
        echo "$text<br> ";
        $cho = $pdo->prepare("SELECT id from choices where `text` = $text");
        $cho->execute();
        $r = $cho->fetch(PDO::FETCH_ASSOC);
        echo $r;
    }
}

Upvotes: 1

Views: 15875

Answers (1)

Dharman
Dharman

Reputation: 33295

Your prepare statement is wrong. You need to replace the PHP variable with a placeholder and then pass the actual value to the execute function.

$cho = $pdo->prepare("SELECT id FROM choices WHERE `text` = ?");
$cho->execute([$text]);
$r = $cho->fetch(PDO::FETCH_ASSOC);

Upvotes: 5

Related Questions