Johanna Cristine Dy
Johanna Cristine Dy

Reputation: 495

DELETE FROM table WHERE IN() prepared statement deletes only the first value of array

through ajax you get an array for $_POST.

This is my code.

<?php
include 'connect.php';
$deletethesestring = '';
foreach ($_POST as $v)
{

    $deletethesestring .= $v.',';

}

$deletethesestring  = rtrim($deletethesestring ,',');

echo $deletethesestring;



$deleteprizesqry = $pdo->prepare('DELETE FROM tbname where tbname_id IN(:deletethesestring);');
$deleteprizesqry  -> bindParam(':deletethesestring', $deletethesestring);

$deleteprizesqry->execute();
?>

if my array is for example [9,7,3,4,8,5] my code only deletes 9. and the rest still stay. I want it to delete every row whose id belongs in the array. how do i do this?

Upvotes: 2

Views: 107

Answers (1)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

Please try below code:

<?php
include 'connect.php';
$deletethesestring = '';
foreach ($_POST as $v)
{

    $deletethesestring .= $v.',';

}

$deleteIds  = rtrim($deletethesestring ,',');

$deletethesestring = join(',', array_fill(0, count($_POST), '?'));

$delQry = "DELETE FROM tbname where tbname_id IN($deletethesestring)";
$deleteprizesqry = $pdo->prepare($delQry);
$deleteprizesqry->execute($_POST);

Hope this help you well!

Upvotes: 3

Related Questions