简体   繁体   中英

What's wrong with my pdo mysql prepared statement?

I have a pdo prepared statement that doesn't work. Can you please help me? I will include some code and the error. Don't pay much attention to the included database.php file. It only stores variables needed for the new PDO.

include('mysql/database.php');
$dbcheck_email_validation=$_POST["email_validation_ajax"];
$dbcheck_email_validation=htmlspecialchars($dbcheck_email_validation);
$dbcheck_email_validation=mysql_real_escape_string($dbcheck_email_validation);
$sql_query = "SELECT * FROM users WHERE email = ?";
$query = $create_pdo->prepare($sql_query);
$query->execute(array($dbcheck_email_validation));
$query->setFetchMode(PDO::FETCH_ASSOC);
$row_from_query = $query->fetch();
$dbcheck_email_validation_assoc=$row_from_query['email'];
echo json_encode($dbcheck_email_validation_assoc);

And the error

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1045]      Access denied for user ''@'localhost' (using password: NO)' in /home/letsrate/public_html/favorit/ajax/ajax_email_validation.php:6Stack trace:#0 /home/letsrate/public_html/favorit/ajax/ajax_email_validation.php(6): PDO->__construct('mysql:host=;dbn...', NULL, NULL)#1 {main} thrown in /home/letsrate/public_html/favorit/ajax/ajax_email_validation.php on line 6

Remove this line:

  $dbcheck_email_validation=mysql_real_escape_string($dbcheck_email_validation);

You can't use mysql functions with PDO.

PDO does the escaping for you anyway, so there's no need for this.

just for sake of code DRYness

include('mysql/database.php');
$query = $create_pdo->prepare("SELECT email FROM users WHERE email = ?");
$query->execute(array($_POST["email_validation_ajax"]));
echo json_encode($query->fetchColumn());

This is all the code you really need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM