如何使用MySQL将数组插入php中的数据库?

时间:2014-03-19 17:08:16

标签: php mysql

我的代码是:

<?php
include("connect.php");
mysql_select_db("cars",$conec);
car = array("BMW","Rolls-Royce","Lamborghini","Mustang");
color = array("red","green","blue","yellow"); 
?>

我想要做的是将每辆车插入一个数据库,这是我试图做的但是我只得到id增加,因为它是一个自动增量。这是我在下面的插入代码:

for($i = 0; $i < 4; $i++){
    $res = mysql_query("insert into auto (car,colors) values ('$car[$i]','$color[$i]')");
}

3 个答案:

答案 0 :(得分:0)

修改

经过测试和运作

<?php
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');  
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_NAME', 'xxx');

$mysqli = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) 
OR die("could not connect");

$car = array("BMW","Rolls-Royce","Lamborghini","Mustang");
$color = array("red","green","blue","yellow");

for($i = 0; $i < 4; $i++){
    $res = mysqli_query($mysqli,"insert into auto (car,colors) values ('$car[$i]','$color[$i]')");
}
?>

如果这是您发布的实际代码:

您忘记了$car个变量的color个符号。

 car = array("BMW","Rolls-Royce","Lamborghini","Mustang");
^-- // here
 color = array("red","green","blue","yellow"); 
^-- // and here

<?php
include("connect.php");
mysql_select_db("cars",$conec);
$car = array("BMW","Rolls-Royce","Lamborghini","Mustang");
$color = array("red","green","blue","yellow"); 
?>

答案 1 :(得分:0)

我认为将PHP数组放在MySQL中通常是不受欢迎的,因为它们只能由PHP读取。你应该运行

$car = json_encode($car);
$color = json_encode($color);

然后当你想从数据库中拉出信息时

$car = json_decode($mysqlcarvarhere);
$color = json_decode($mysqlcolorvarhere);

此外,在您的第二位代码中,将“$ car [$ i]”插入到该数据库中,而不是将$ car ['$ i']的值插入到数据库中。要解决此问题,您应该将查询更改为:

$res = mysql_query("insert into auto (car,colors) values ('" . $car[$i] . "','" . $color[$i] ."')");

此外,通用的“你应该切换到PDO / MySQLi,否则你会被黑客攻击”这里的演讲。

答案 2 :(得分:0)

我建议您使用Prepared Statement,用于各种reasons

假设已经建立了与数据库的连接,这是一种方法:

<?php
    include("connect.php");

    $cars = array("BMW","Rolls-Royce","Lamborghini","Mustang");
    $colors = array("red","green","blue","yellow"); 

    $db = new mysqli($host, $user, $password, $database);
    $stmt = $db->prepare("INSERT INTO auto(car, color) VALUES(?, ?)");

    // Here I deliberately assume that all car has every color variant
    foreach($cars as $car) {
        foreach($colors as $color) {
            $stmt->bind_param('s', $car);
            $stmt->bind_param('s', $color);

            $stmt->execute();
        }
    }

    $stmt->close();

?>

如何使用Prepared Statement解决它只是一个粗略的想法,你总是可以将它包装在函数或类中。