1

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; } } 
1
  • 1
    You are not using the prepare properly, = $text"should be = ?" and then execute([$text]) Commented Jul 6, 2019 at 16:27

1 Answer 1

5

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Dharman, it's working now. But you know most of the time such problems works without using placeholder, then why is it not working?
Most of the time it works 60% of the time. You might be lucky it works, but if you do it properly it will work 100%. Prepared statements with placeholders are the correct way to do it and the side effect is that they protect you from SQL injection too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.