简体   繁体   中英

How to delete record in bulk using php

$id=array(1,3,5);
$sql="delete * from tablename where id = ".$id; 

Now I want to delete all record in mysql whose $id are 1,3 and 5 at once..

DELETE FROM `tablename` WHERE id IN (1, 3, 5);

With PDO:

$ids = array(1, 3, 5);
/* Create a string for the parameter placeholders filled to the number of params */
$place_holders = implode(',', array_fill(0, count($ids), '?'));

/*
    This prepares the statement with enough unnamed placeholders for every value
    in our $ids array. The values of the $ids array are then bound to the
    placeholders in the prepared statement when the statement is executed.
*/
$stmt = $dbh->prepare("DELETE FROM tablename WHERE id IN (" . $place_holders . ")");
$stmt->execute($ids);

deleting with an id:

DELETE FROM `tablename` WHERE id = 1;

with IN clause:

DELETE FROM `tablename` WHERE id IN (1, 3, 5);

delete all content from the given table

TRUNCATE table `tablename`;

deleting with given array of elements:

foreach($id as $i) {
    $sql="delete * from tablename where id = ".$i;
}
$id=array(1,3,5);
$ids = implode(",",$id);
$sql="delete * from tablename where id IN (".$ids.")";

use the above code.

You first need to convert your array to the normal string,

$ids = array(1, 3, 5);
$strngId = implode(",",$ids);

now with this variable you can write delete query.

$sql = "Delete * from tablename where idfield IN (".$strngId.")";

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