从数据库中删除多个值

时间:2014-08-29 12:07:03

标签: mysql delete-row

我正在使用此文件从服务器删除记录

<?php

$dbhandle = mysql_connect("localhost", "admin", "admin") or die(mysql_error()) ; 
$selected =  mysql_select_db("dbname" ,$dbhandle) or die(mysql_error()) ; 


$id=$_POST['id'];

foreach($id as  $value)
{

 $query = mysql_query("DELETE FROM `record` WHERE `id`=$value");
}
 mysql_close($dbhandle);
?>

但我无法从数据库中删除记录。查询正在执行而没有任何错误,但它无法从表中删除记录

2 个答案:

答案 0 :(得分:3)

$query = mysql_query('DELETE FROM `record` WHERE `id` IN (' . implode(',', array_map('intval', $id)) . ')');

答案 1 :(得分:0)

即使$id数组不包含整数,这也会有效。

class db {
    private static $instance = NULL;
    private function __construct() {}   //Make private
    private function __clone(){}   //Make private
    public static function db() //Get instance of DB
    {
        if (!self::$instance)
        {
            self::$instance = new PDO("mysql:host=localhost;dbname=myDB;charset=utf8",'myUsername','myPassword',array(PDO::ATTR_EMULATE_PREPARES=>false,PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true,PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC));
        }
        return self::$instance;
    }
}

if(count($ids)) {  //Make sure you don't have an empty data set.
  $qMarks = str_repeat('?,', count($ids)-1) . '?';
  $sql ="DELETE FROM `record` WHERE `id` IN ({$qMarks})";
  $stmt = $db::db->prepare($sql);
  $stmt->execute($id);
}