PHP Implode But Wrap Each Element In Quotes

耗尽温柔 提交于 2019-12-02 16:35:15

Add the quotes into the implode call: (I'm assuming you meant implode)

$SQL = 'DELETE FROM elements
           WHERE id IN ("' . implode('", "', $elements) . '")';

This produces:

DELETE FROM elements WHERE id IN ("foo", "bar", "tar", "dar")

The best way to prevent against SQL injection is to make sure your elements are properly escaped.

An easy thing to do that should work (but I haven't tested it) is to use either array_map or array_walk, and escape every parameter, like so:

$elements = array();
$elements = array_map( 'mysql_real_escape_string', $elements);
insign

You can use array_walk to iterate all the elements in side the array passing the reference to the element and add the quotes in the following way.

<?php

$arr = ['a','b','c'];

array_walk($arr, function(&$x) {$x = "'$x'";});

echo implode(',', $arr); // 'a','b','c'

?>

You can run a simple array_map() function to wrap the strings in quotes and then wrap that around the implode() to add the commas:

$array = ["one", "two", "three", "four"];

implode(",", array_map(function($string) {
    return '"' . $string . '"';
}, $array));

Just to add to the top answer a bit here, even if you are using MySQLi it is possible to call real_escape_string using array_map by using the object method callable form. Here is an example, assuming $conn is your MySQLi connection:

$elements = array('foo', 'bar', 'tar', 'dar');
$cleanedElements = array_map([$conn, 'real_escape_string'], $ids);
$SQL = 'DELETE FROM elements WHERE id IN ("' . implode('", "', $elements) . '")';

Note that the first parameter of array_map is an array with the object followed by the method name. This is the same as executing the following for each item in the array:

$newItem = $conn->real_escape_string($item);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!