Jump to content

Using array in query


V

Recommended Posts

I'm trying to delete items from a table by selecting them via checkboxes. I managed to post all the ids of the checkboxes I filled in the url like this,

 

check_box=154,153,152    etc...

 

and turned that into an array

 

Array
(
    [0] => 154
    [1] => 153
    [2] => 152
)
Array

 

using

 

$delete_selected = $connection->real_escape_string($_POST['check_box']);
$check_box_array = explode(",", $delete_selected);

 

Now I can't figure out how to put that into

 

$sql = "DELETE FROM categories WHERE cat_id = '$delete_selected'";

 

it only deletes one. Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/209446-using-array-in-query/
Share on other sites

Instead of turning POST['check_box'] into an array.  Keep it like it is, with the commas and just "clean" it.  As in mysql_real_escape_string()

 

Then use MySQL's IN function to look through all of them

$sql = "DELETE FROM categories WHERE cat_id IN (" . mysql_real_escape_string($_POST['check_box']) . ")";

Zanus that's the best solution! Thanks :) I tried so many other things.

 

I tried putting the $delete_selected var in the sql but it doesn't work.

 

$delete_selected = $connection->real_escape_string($_POST['check_box']);

$sql = "DELETE FROM categories WHERE cat_id IN ('$delete_selected')";

 

I'm using mysqli object oriented so I get errors errors when using mysql_real_escape_string  in the query :-\

Almost,

 

I get

 

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given in C:\wamp\www\gisttest\save_category.php on line 34

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1

 

it only works with

 

$sql = "DELETE FROM categories WHERE cat_id IN (" . $_POST['check_box'] . ")";

 

without the escape string.

MySQLi_real_escape_string expects you to put the connection variable as the first parameter.

 

Though, the $connection->real_escape_string() method you used should have worked.  Regardless, escaping the string isn't a MUST for it to work, but it is a must if you want it secure.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.