简体   繁体   English

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

[英]How to insert array value in Implode form in mysql

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. 我有以下格式的值,我想将此键和值转换为内爆形式,以便在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 我在MYSQL中有2列“键”和“值”,并将上述值以爆破形式存储在此字段中,类似于此键:

Value:3.46m³, 2, 2,2 价值:3.46m³,2,2,2

You could use bindParam ( PHP docs ) and write your queries like so: 您可以使用bindParamPHP docs )编写查询,如下所示:

$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";
}

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;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM