PDO PHP insert into DB from an associative array

前端 未结 6 947
鱼传尺愫
鱼传尺愫 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条回答
  •  Happy的楠姐
    2020-12-06 07:44

    You actually can have the :phone and :image fields bound with null values in advance. The structure of the table is fixed anyway and you probably should got that way.


    But the answer to your question might look like this:

    $keys = ':' . implode(', :', array_keys($array)); 
    $values = str_repeat('?, ', count($array)-1) . '?';
    
    $i = 1;
    $q = $DBH->prepare("INSERT INTO user ($keys) VALUES ($values)");
    
    foreach($array as $value)
        $q->bindParam($i++, $value, PDO::PARAM_STR, mb_strlen($value));
    

提交回复
热议问题