如何在其字段中将php多维数组数据存储到数据库中

时间:2018-09-08 14:37:56

标签: php mysql

我有多个数组数据,例如“汽车名称和汽车模态”

汽车名称与汽车型号匹配。两者都是数据库中的不同列(cars_name,cars_model)。我想将此数组中的数据存储到其字段中的数据库中

输出:

    Array
(
    [car_name] => Array
        (
            [0] => Honda
            [1] => Ford Mustang
            [2] => Volvo
        )

    [car_modal] => Array
        (
            [0] => 2015
            [1] => 2016
            [2] => 2014
        )

)

我想使用“ mysql ”将数组值存储到每一行的单个列中。为此,我喜欢这样的查询,但显示错误。

$sql = "INSERT INTO cars_data (cars_name,cars_modal)
VALUES ($cars_name,$cars_modal)";

什么都没发生。但是错误显示如下……

  

通知:数组到字符串的转换    45 行的E:\ xampp \ htdocs \ car_records \ modal_data.php 错误:插入INTO CARS_DATA(CARS_NAME,CARS_MODE)

     

VALUES(数组,数组)
“字段列表”中的未知列“数组”

问题是如何修复它。请帮助我

3 个答案:

答案 0 :(得分:0)

您可以在一行中插入多个元素,只需将其以正确的格式显示即可:

  

插入x(列)值(x1),(x2),(x3)

$string = "";
foreach($cars_name as $car){
    $string .= "(" . $car . "), ";
}
$sql = "INSERT INTO car_data (cars_name) VALUES $string";

请注意,您必须对用户输入进行未经消毒的处理。

答案 1 :(得分:0)

要使用一个语句和mysqli准备好的语句(代码中的注释)...

$cars_name = ["Honda", "Volvo"];
// Create an entry for each name
$params = str_repeat("(?),", count($cars_name));
// Build a bind for a list of strings
$binds = str_repeat("s", count($cars_name));
// Add the params to the insert (remove the last ,)
$sql = "INSERT INTO car_data (cars_name)
             VALUES ".rtrim($params, ",");

$insert = $conn->prepare ( $sql );
// Bind the parameters, using ... is the argument unpacking operator
$insert->bind_param($binds, ...$cars_name);
// Execute the SQL
$insert->execute();

更新

如果数组中有两个数据项,则可以使上面的内容适用于......

// Source data - ensure that the two sets of data have the same number of entries
$car_data = [ 'cars_name' => ["Honda", "Volvo"],
        'cars_modal' => [ '2015', '2016' ]];
$car_count = count($car_data['cars_name']);
// Create an entry for each name (2 binds per entry)
$params = str_repeat("(?,?),", $car_count);
// Build a bind for a list of strings
$binds = str_repeat("ss", $car_count);
// Reformat data for binding (needs to be a single list of the data
// with cars_name followed by cars_modal for each entry)
$merged_data = [];
foreach ( $car_data['cars_name']  as $key => $name )    {
    $merged_data[] = $name;
    $merged_data[] = $car_data['cars_modal'][$key];
}   
// Add the params to the insert (remove the last ,)
$sql = "INSERT INTO car_data (cars_name,car_model)
                 VALUES ".rtrim($params, ",");

$insert = $conn->prepare ( $sql );
// Bind the parameters, using ... is the argument unpacking operator
$insert->bind_param($binds, ...$merged_data);
// Execute the SQL
$insert->execute();

答案 2 :(得分:0)

当我想这样做时,我首先对这个数组进行内插处理,得到一个以(,)分隔的普通字符串,然后在检索数据时再次对它们进行内插处理。

   $cars_name = implode(',', $_POST['cars_name']);

结果将是

   Honda,Volvo,Mercedes,Toyota,BMW

然后,如果您想再次从数据库中取回阵列,请执行以下操作:

   $cars_array = explode(',', $databaseObject['cars']);

结果将与您的第一个数组相同。