Sql delete返回删除的0行

时间:2012-01-17 20:05:37

标签: php pdo

    ...
    $count = $conn->exec("
        DELETE FROM date_practice 
        WHERE  date between '.$dateBefor.' AND '.$dateAfter.' 
    ");

    print("Deleted $count rows.\n"); 
} catch (PDOException $e) {
    echo $sql . '<br />' . $e->getMessage();
} 
$conn = NULL; 
?>

打印已删除的0行。

2 个答案:

答案 0 :(得分:3)

问题是你的.(连接运算符)在你的双引号内,所以它们被认为是它们的一部分。这个发送的文字查询将如下所示:

DELETE FROM date_practice WHERE date between '.2011-01-01.' and '.2011-12-31.'

试试这个:

$count = $conn->exec(
  "DELETE FROM date_practice " .
  "  WHERE date BETWEEN '$dateBefor' AND '$dateAfter'"
);

更好的是,因为你已经在使用PDO prepared statements,它会为你担心变量插值并保护你免受SQL注入攻击:

$stmt = $dbh->prepare(
  'DELETE FROM date_practice ' .
  '  WHERE date BETWEEN :before AND :after'
);

$stmt->bindParam(':before', $dateBefor);
$stmt->bindParam(':after',  $dateAfter);

$stmt->execute();

echo 'Deleted ', $stmt->rowCount(), ' rows.';

答案 1 :(得分:0)

您的查询应如下所示

$count = $conn->exec("DELETE FROM date_practice WHERE  date between '$dateBefor' and '$dateAfter' ");

日期周围可能没有''。我们不知道您使用的格式以及您的数据库接受的内容。