dtlrp119999
2019-03-14 03:23 阅读 439
已采纳

如何在mysql中以Implode形式插入数组值

I have a value in below format and i want to convert this key and value in implode form to insert value in database in mysql.

 Array
(
[users_ids] => 
[key_name] => Total_Cubic_Metres
[value_name] => 3.46m³
)

Array
(
[users_ids] => 
[key_name] => Bedroom_Bassinette
[value_name] => 2
)

Array
(
[users_ids] => 
[key_name] => Bedroom_Bedside_Drawers
[value_name] => 2
)

Array
(
[users_ids] => 
[key_name] => Bedroom_Bedside_Table
[value_name] => 2
)

I have 2 COLUMN in MYSQL "key" and "value" and store the above value in this field in implode form something like this key:Total_Cubic_Metres,Bedroom_Bassinette,Bedroom_Bedside_Drawers,Bedroom_Bedside_Drawers,Bedroom_Bedside_Table

Value:3.46m³, 2, 2,2

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dtz46697 dtz46697 2019-03-14 03:37

    You could use bindParam (PHP docs) and write your queries like so:

    $my_Insert_Statement = $my_Db_Connection->prepare("
    INSERT INTO TABLE_NAME (
      Total_Cubic_Metres,
      Bedroom_Bassinette,
      Bedroom_Bedside_Drawers,
      Bedroom_Bedside_Drawers,
      Bedroom_Bedside_Table) 
    VALUES (
     :Total_Cubic_Metres,  
     :Bedroom_Bassinette,
     :Bedroom_Bedside_Drawers,
     :Bedroom_Bedside_Drawers,
     :Bedroom_Bedside_Table
    )");
    

    and you could add them like:

    foreach($arr as $colData){
      $my_Insert_Statement->bindParam($colData['key_name'], $colData['value_name']);
    }
    

    and execute the prepared statement:

    if ($my_Insert_Statement->execute()) {
      echo "New record created successfully";
    } else {
      echo "Unable to create record";
    }
    
    点赞 评论 复制链接分享
  • dsvtnz6350 dsvtnz6350 2019-03-14 04:22

    Try below code

     function insertQuery($table, $dataArray, $connection){
        $dataArray = array_map(array($connection, 'real_escape_string'), $dataArray);
        $keys = array_keys($dataArray);
        $colmuns = implode(",",$keys);
        $values =array_values($dataArray);
        $valueData = implode("','",$values);
        $query = "INSERT INTO $table ($colmuns) VALUES ('$valueData')";
        $result = mysqli_query($connection, $query);
    
        if($result){
          $id = mysqli_insert_id($connection);
          return $id;
        }
        return false;
     }
    
    点赞 评论 复制链接分享

相关推荐