简体   繁体   English

将数组的多个值插入数据库

[英]Inserting multiple values of an array into database

I am trying to read a file of data and insert into a table in mySQL. 我正在尝试读取数据文件并将其插入到MySQL中的表中。 I have tried building an array and imploding, as well as a foreach loop like this one but only get back the first row of the table. 我试过建立一个数组和内爆,以及像这样的foreach循环,但只返回表的第一行。

<?php 
$str = file_get_contents('-');
$con = mysqli_connect('-', '-', '-','-');
$dataArray = explode("|",$str);
$blahArray = array();
foreach($dataArray as $info){
            $pD = unserialize($info);
            $pD->*->*->*;
            $pL = $pD->*->*->*[0];
            $blah = $pL->BLAH;
            array_push($blahArray,$blah);       
}
foreach($blahArray as $val){
            $sql = "INSERT INTO table (BLAH)
                    VALUES('$val')";            
            mysqli_query($con,$sql);
            }
?>

I have a lot more datafields to enter but for debugging am just trying the one. 我有很多数据字段要输入,但是要调试,只能尝试其中的一个。 Any help or suggestions would be greatly appreciated! 任何帮助或建议,将不胜感激!

Try this: 尝试这个:

$sql = "INSERT INTO property (APN)
                    VALUES";
foreach ($apnArray as $val) {
    $sql .= "('$val'),";
}
$sql = trim($sql, ",");
mysqli_query($con, $sql);

I can't say for certain what is wrong with your code, but here is a modification you can make which might tell you what is going on: 我无法确定您的代码有什么问题,但是您可以进行以下修改,以告诉您发生了什么事情:

foreach($apnArray as $val) {
    $sql = "INSERT INTO property (APN) VALUES('$val')";            
    $result = mysqli_query($con, $sql);
    if (false===$result) {
        printf("error: %s\n", mysqli_error($con));
    }
}

Check for two things. 检查两件事。 First, make sure that you are in fact looping 90 times. 首先,请确保您实际上循环了90次。 Second, see if each INSERT query be executing with or without error. 其次,查看每个INSERT查询是否正在执行,有无错误。

Update: 更新:

Based on your comment, it appears that you have a primary key with a unique constraint, which is not set to autoincrement. 根据您的评论,您似乎拥有一个具有唯一约束的主键,该约束设置为自动增量。 In your INSERT query, you are only setting a value for the APN column and nothing else. INSERT查询中,您只为APN列设置一个值,而没有其他设置。 This means that MySQL is using a default value (0) for this primary key. 这意味着MySQL正在为此主键使用默认值(0)。 The solution to your problem is to pass in a unique value for the primary key or to set that primary key column to autoincrement. 解决您的问题的方法是为主键传递唯一的值, 或者将该主键列设置为自动递增。

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

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