PHP how to quote string array values
arrays, mysql, php, string
Solution
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]);
Problem
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)"; ```