DELETE语句不会删除行

时间:2015-08-20 12:34:08

标签: php mysql sql pdo

你可以看到我在这里的表:

enter image description here

我现在用随机值填充它,因为我只想检查代码是否有效。我正在使用的代码如下:

try {

    $tempdel = $pdo->prepare("DELETE FROM splatoon_players WHERE id = 1;
    DELETE FROM splatoon_players WHERE id = 2;
    DELETE FROM splatoon_players WHERE id = 3;
    DELETE FROM splatoon_players WHERE id = 4;
    DELETE FROM splatoon_players WHERE id = 5;
    DELETE FROM splatoon_players WHERE id = 6;
    DELETE FROM splatoon_players WHERE id = 7;
    DELETE FROM splatoon_players WHERE id = 8;");
    $tempdel->execute();

   } catch (PDOException $e) {

    $error = "Unable to execute the query. ". $e->getMessage();
    exit();

   } 

我花了差不多一个小时来找出错误的位置,但我无法得到它。我当然正在使用PDO课程。

如果我在phpmyadmin shell中执行所有8个查询,它们可以正常工作,但是使用上面的代码运行* .php脚本它们不起作用。

当我说“它们不起作用”时,我只是说这些行仍然在表中而不是被删除。删除不会发生。有什么想法吗?

3 个答案:

答案 0 :(得分:6)

注意:我想我第一次错过了execute。嗯。 。 。准备语句不会执行它。因此,您的代码只是在应用程序中进行字符串操作和设置数据结构。它没有运行代码。

在任何情况下,执行通常都会执行一个语句。请参阅此question

但你应该将其表达为一个查询:

DELETE FROM splatoon_players WHERE id in (1, 2, 3, 4, 5, 6, 7, 8);

一个查询更有效。

答案 1 :(得分:1)

$ids = array(1,2,3,4,5,6,7,8);
$stmt = $pdo->prepare("DELETE FROM splatoon_players WHERE id = ?");
foreach ($ids as $id)
{
    $stmt->execute(array($id));
}

$ids = array(1,2,3,4,5,6,7,8);
$in  = str_repeat('?,', count($ids) - 1) . '?';
$sql = "DELETE FROM splatoon_players WHERE id IN ($in)";
$db->prepare($sql)->execute($ids);

是您需要的所有代码 Do not use try-catch for the basic error reporting

答案 2 :(得分:-1)

尝试使用此

try {
        $ids = array('1','2','3','4','5','6','7','8');

        foreach ($ids as $id) {
            $tempdel = $pdo->prepare("DELETE FROM splatoon_players WHERE id = ". $id ."");
            $tempdel->execute();
        }
   } catch (PDOException $e) {

    $error = "Unable to execute the query. ". $e->getMessage();
    exit();

   }