PHP how to quote string array values
Solution 1
Better use prepared queries. But just for funs sake:
implode(',', array_map(function($value) {
if(!is_numeric($value)) {
return '"' . $value . '"';
//adds double quotes, but if you prefer single quotes, use:
//return "'" . $value . "'";
} else {
return $value;
}
}, $array[0]);
Solution 2
Agree that you should look at prepared statements, however to answer your original question you can do that like this:
$array=array('a', 'b', 'c');
$string = "'" . implode("','", $array) . "'";
Ares Draguna
My philosophy in life: We can change the world if God gives us the source code
Updated on June 14, 2022Comments
-
Ares Draguna almost 2 years
If I have the following array
$array[0] = array( "1" => bar, "2" => foo, "3" => 13546 );
and I implode() it, the value that is returned will be:bar,foo,13546
which cannot be used in a mysql query... How can I place single quotes just to those values that are strings...I've tryed a couple of ways (like
foreach($array as $key=>$value)
to check with is_numeric() the $value, and the check is ok but I dont know how to change the value to '$value'...)Any toughts on this?
EDIT
I found another way to do this for those of you who are interested:
$result[0] = array( "1" => bar, "2" => foo, "3" => 1232.13 ); $copy_r = $result[0]; foreach($copy_r as $key=>$value) { if(!is_numeric($value)) { $insert_array[] = "`$key` = '$value'"; } else { $insert_array[] = "`$key` = $value"; } } $final_string = implode(',', $insert_array); $insert_q = "INSERT INTO `table_name` SET $final_string ON DUPLICATE KEY UPDATE ($final_string)";
-
scenia about 10 yearsHe wants to surround only string values with
'
, numeric values are supposed to remain blank. -
trincot over 6 yearsYou should use prepared statements as this just keeps open the SQL injection vulnerability. Also, this quotes everything, which was not what the OP asked. Finally, using
array_filter
to mutate an array is bad practice. -
S.Joshi over 6 yearsQuestions: 1. I am just creating a string here and storing it in variable that i can use in my php code like IN ($arr), so how will this keep the system vulnerable?
-
S.Joshi over 6 yearsand should i use array_map() for this purpose?
-
trincot over 6 yearsI will not explain SQL injection here. Just one example: when
$arr
contains a value like') or 1=1 or 'x' in ('
, then the SQL statement will not have the desired effect. (2) you should usearray_map
and not mutate the array in the function, but return the modified values, and use the return value ofarray_map
.