seoppc
seoppc

Reputation: 2824

Bulk action using PHP for mysql entries

We are showing results in a table from a MySQL database with checkboxes inside it. How can we delete many rows simultaneously if the user ticks 5 rows and clicks the delete button?

Upvotes: 0

Views: 1266

Answers (3)

hsz
hsz

Reputation: 152216

HTML:

<form method="post">

    <input type="checkbox" name="id[]" value="123" /> Element 1 <br/>
    <input type="checkbox" name="id[]" value="5434" /> Element 2 <br/>
    <input type="checkbox" name="id[]" value="24" /> Element 3 <br/>
    <input type="checkbox" name="id[]" value="76" /> Element 4 <br/>

    <input type="submit" value="delete" />

</form>

PHP:

if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {

  $ids = array_walk($_POST['id'], 'intval');
  mysql_query('DELETE FROM table WHERE id IN (' . implode(',', $ids) . ')');

}

P.S. I want points !

Upvotes: 2

JuanToroMarty
JuanToroMarty

Reputation: 506

With PDOStatement like this

$statement = "DELETE FROM table WHERE id = ?";
$conn = new PDO($dns,$user,$pass);
$conn->beginTransaction();
$query = $conn->prepare($statement);
foreach($params as $p){ //$params are your checked id's
    $query->bindParam(1,$p);
    if($query->execute()){
        echo "ok";
    }else{
        $conn->rollBack();
        exit("Error");
    }
}
$conn->commit();

Upvotes: 1

tobyS
tobyS

Reputation: 870

I won't give you the PHP code, but building an SQL query like this will solve your problem:

DELETE FROM foo WHERE id IN ( … );

See the manual for details.

Upvotes: 1

Related Questions