PDO PHP insert into DB from an associative array

前端 未结 6 967
鱼传尺愫
鱼传尺愫 2020-12-06 07:01

I have an array like this

  $a = array( \'phone\' => 111111111, \'image\' => \"sadasdasd43eadasdad\" );

When I do a var-dump I get th

6条回答
  •  醉酒成梦
    2020-12-06 07:21

    Last time I checked, it was not possible to prepare a statement where the affected columns were unknown at preparation time - but that thing seems to work - maybe your database system is more forgiving than those I am using (mainly postgres)

    What is clearly wrong is the implode() statement, as each variable should be handled by it self, you also need parenthesis around the field list in the insert statement.

    To insert user defined fields, I think you have to do something like this (at least that how I do it);

    $fields=array_keys($a); // here you have to trust your field names! 
    $values=array_values($a);
    $fieldlist=implode(',',$fields); 
    $qs=str_repeat("?,",count($fields)-1);
    $sql="insert into user($fieldlist) values(${qs}?)";
    $q=$DBH->prepare($sql);
    $q->execute($values);
    

    If you cannot trust the field names in $a, you have to do something like

    foreach($a as $f=>$v){
       if(validfield($f)){
          $fields[]=$f;
          $values[]=$v;
       }
    }
    

    Where validfields is a function that you write that tests each fieldname and checks if it is valid (quick and dirty by making an associative array $valfields=array('name'=>1,'email'=>1, 'phone'=>1 ... and then checking for the value of $valfields[$f], or (as I would prefer) by fetching the field names from the server)

提交回复
热议问题