简体   繁体   中英

How to use MySQL IN with Joomla query - Syntax Issue

I have a variable called $del_ids which is using the array_keys() function:

$del_ids = implode("','", array_keys($_POST['gallery']));

$del_ids outputs an array that looks like this:

Array
(
    [2] => on
    [4] => on
)

And I need to delete any rows which have an id which matches IN the array. If I use procedural PHP it works great:

$query = "DELETE FROM studio_sessions WHERE id IN('$del_ids')";
$result = mysqli_query($connection, $query);

When I convert this to Joomla query, I can't get the IN syntax correctly. For example:

$db = JFactory::getDbo();
$query = $db->getQuery(true);

$conditions = array(
    $db->quoteName('id' . ' IN ' . $del_ids) 
);

$query->delete($db->quoteName('#__studio_sessions'));
$query->where($conditions);

$db->setQuery($query);
$result = $db->execute();

I get this error:

1054 Unknown column 'id IN 2','4' in 'where clause' SQL=DELETE FROM `vsem6_studio_sessions` WHERE `id IN 2','4` 

Looks like I'm missing some single quotes maybe around the id and 2, but I can't get the syntax right - can anyone spot the issue?

$db->quoteName('id' . ' IN ' . $del_ids)

Is incorrect. You are treating that whole long strng as a name which is why it thinks that 'id IN('2','4')' is the column name.

Try $db->quoteName('id') . ' IN (' . $del_ids .')' $db->quoteName('id') . ' IN (' . $del_ids .')'

Also your initial implode should be

$del_ids = implode(',', array_keys($_POST['gallery']));

Otherwise you will get ',' as the separator rather than ' .

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