PHP how to quote string array values

13,511

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) . "'";
Share:
13,511
Ares Draguna
Author by

Ares Draguna

My philosophy in life: We can change the world if God gives us the source code

Updated on June 14, 2022

Comments

  • Ares Draguna
    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
    scenia about 10 years
    He wants to surround only string values with ', numeric values are supposed to remain blank.
  • trincot
    trincot over 6 years
    You 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
    S.Joshi over 6 years
    Questions: 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
    S.Joshi over 6 years
    and should i use array_map() for this purpose?
  • trincot
    trincot over 6 years
    I 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 use array_map and not mutate the array in the function, but return the modified values, and use the return value of array_map.