致命错误:未捕获的PDO异常:SQLSTATE [42000]语法错误或访问Vilation

时间:2018-05-13 19:29:06

标签: php mysql sql database pdo

我正在实施一个简单的代码来检查我的数据库中是否有一封电子邮件,以及是否正在从数据库中删除它。但是,我收到此错误消息:

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 
'@gmail.com' at line 1 in /home/saintpao/public_html/deleteNewsletter.php:24 Stack 
trace: #0 /home/saintpao/public_html/deleteNewsletter.php(24): 
PDOStatement->execute() #1 {main} thrown in /home/saintpao/public_html
/deleteNewsletter.php on line 24

这是conectar.php文件

$dbhost = "myHost";
$dbuser = "myUser";
$dbpass = "myPassword";
$dbname = "myDBName";
try {
    $db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass,  
                  array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"));
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(Exception $error) {
    die("Error conexión BBDD " . $error->getMessage());
}   

这是deleteNewsletter.php文件:

function sanitazeEmail($email){
   if(empty($email)){
       return "";
   }
   $sanitized = filter_var($email, FILTER_SANITIZE_EMAIL);
   if(filter_var($sanitized, FILTER_VALIDATE_EMAIL)){
       return $sanitized;
   }
   return "";
}

$success = false;
$email = sanitazeEmail($_POST['email']);

if(!empty($email)){
    require_once 'conectar.php';

    $sql = "SELECT `email` FROM `emails` WHERE `email` = " . $email;
    $statement = $db->prepare($sql);

    if($statement->execute()){
        $sql_delete = "DELETE FROM `emails` WHERE `email` =" . $email;
        $statement = $db->prepare($sql_delete);
        $success = $statement->execute();
    }
}

与数据库的连接有效,因为我能够在其他文件中进行SELECT请求,因此它必须是deleteNewsletter.php文件的问题。知道什么是错的吗?

1 个答案:

答案 0 :(得分:2)

您的错误是电子邮件是字符串,应该引用。但是,您正在使用PDO,您可以使用预准备语句来避免此类错误:

connect

请注意,您的onCreate查询确实没用,您可以执行$sql_delete = "DELETE FROM `emails` WHERE `email` = :email"; $statement = $db->prepare($sql_delete); $sucess = $statement->execute([':email' => $email]); 查询。请注意,select返回一个语句,而不是结果。

正如@NigelRen指出的那样,您可以使用delete来检查是否删除了一行。