Jump to content

using an array as variable in delete query


WesleyA

Recommended Posts

Is it possible to use an array, so a range of numbers to delete records from a table?

 

This is the normal query

     $sql = "DELETE FROM MyGuests WHERE id=3";

But this only deletes one record.

 

I have several numbers and I would like to use an array but I'm not sure whether it is possible or not. Can you just use something like

      $sql = "DELETE FROM MyGuests WHERE $_GET['id']";

so var_dump($_GET['id']); would be something like: 5, 8, 14, 88 and all these records would be deleted.

 

Like this:

 

array (size=5)0 => string '7' (length=1)1 => string '11' (length=2)2 => string '15' (length=2)3 => string '17' (length=2)4 => string '21' (length=2)

Edited by WesleyA
Link to comment
Share on other sites

This works:

DELETE FROM MyGuests WHERE id IN (7, 11, 15, 17, 21)

In PHP

// Sanitize inputs!!!foreach($_GET['id'] as &$id) {  $id = (int) $id;}$sql = 'DELETE FROM MyGuests WHERE id IN (' . implode(',', $_GET['id']) . ')';
Link to comment
Share on other sites

Can you explain what ' id ' is in:

 

DELETE FROM table WHERE id .....

 

is it something you identify something with or is it an identical unique number?

 

I would like to find a way to match the unique key and use this key to delete the entire record.

Link to comment
Share on other sites

`id` is the same thing you had in your query. It's just the name of a field in the table.

 

It's no different than

DELETE FROM MyGuests WHERE apple IN (7, 11, 15, 17, 21)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...