Does PHP check a numeric value inside a foreach loop with pairs of keys and values?

I am trying to check the associative value of an array, if it is numeric, here is my code

     $data = array('fullname'=>'Salah Saed', 'age'=>'33', 'gender'=>'Female');



public function insert($data, $table){
    /*$query =  "INSERT INTO  `oop_crud`.`customers` (";
    $query .= "`fullname` , `age` , `gender` )"; 
    $query .= "VALUES ('".$fullname."',  '".$age."',  '".$gender."')";
    */
    $feilds = array(); 
    $feilds_value = array();
    foreach ($data as $field => $field_value){

        $feilds[] = $field;

        echo $field;
        if (is_numeric($field_value)){

            $feilds_value[] = $field_value;

        }else{

            $feilds_value[] = "'".$field_value."'";
        }


    }

    $query = "INSERT INTO ".$table." (";
    $query .= implode(',', $feilds).")";
    $query .= "VALUES (";
    $query .= implode(',',$feilds_value).")";


    echo $query;

It returns a string, therefore, what is wrong with my code, in the conditions section I use the value $ field_value, and this variable has array data, sows how to get the value of the array.

+4
source share
2 answers

First of all, MySQL inserts are type independent, so

SET UserAge = '33'

coincides with

SET UserAge = 33

so you can just add quotes. However, you are most secure if you are looking for prepared statements using PDOs (also called parameterized queries). Look what

http://php.net/is_numeric , 0x539 0b10100111001, MySQL; .

+4

, ,

function insert($data, $table){

    $column_sql = '`' . implode('`,`', array_keys($data)) . '`';

    $record_sql = "'" . implode("','", $data) . "'";

    return "INSERT INTO `{$table}` ({$column_sql}) VALUES ({$record_sql})";

}

$data test

INSERT INTO `test` (`fullname`,`age`,`gender`) VALUES ('Salah Saed','33','Female')

: mysqli_real_escape_string(), , :)

+2

All Articles