简体   繁体   English

通过循环将数组值插入mysql

[英]Insert array values into mysql through loop

I'm reading through xml files with simplexml_load_file. 我正在使用simplexml_load_file读取xml文件。 I'm trying to loop through 3 different xml files and then insert the value into mysql database. 我试图遍历3个不同的xml文件,然后将值插入mysql数据库。 It's only inserting the last array. 它只是插入最后一个数组。 Should I be using a while loop? 我应该使用while循环吗?

Here is my code: 这是我的代码:

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 


// Load/read xml files
$id1 = simplexml_load_file('1.xml');
// echo $id1->video[0];

$id2 = simplexml_load_file('2.xml');
// echo $id2->video[0];

$id3 = simplexml_load_file('2.xml');
// echo $id3->video[0];



// make into an array list
$arr = array($id1->video[0], $id2->video[0], $id3->video[0]);

// loop through array and insert into sql database
foreach ($arr as $value) {
    $value = $value;
    $sql = "INSERT INTO videos (username, src, type, position)
    VALUES ('admin', '".$value."', 'vide', '0')";
}

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

Every time you iterate in the foreach you're overwritting the $sql variable. 每次在foreach中进行迭代时,都会覆盖$ sql变量。 Since you're performing the query after the for loop, only the last item of the array it's being inserted into the DB. 由于在for循环之后执行查询,因此仅将数组的最后一项插入数据库。

To solve it you should put the query inside the for loop: 要解决它,您应该将查询放入for循环内:

foreach ($arr as $value) {
    $sql = "INSERT INTO videos (username, src, type, position)
    VALUES ('admin', '".$value."', 'vide', '0')";

    if ($conn->query($sql)) {
       echo "New record created successfully";
    } else {
       echo "Error: " . $sql . "<br>" . $conn->error;
    }
 }

However you must take care with SQL Injection, I recommend you to take a look at PDO. 但是,您必须小心使用SQL注入,我建议您看一下PDO。 http://php.net/manual/en/ref.pdo-mysql.php http://php.net/manual/en/ref.pdo-mysql.php

Let me transform this into a PDO example: 让我将其转换为PDO示例:

$sql = "INSERT INTO videos (username, src, type, position ) VALUES ('admin', :value, 'vide', '0')";
if ($stmt = $PDO->prepare($sql)) {
    foreach($arr as $value) {
        $binds['value'] = $value;
        if ($stmt->execute($binds)) {
            echo "Row inserted successfully"
        } 
    }
}

$PDO would be the variable where the conexion is stored. $ PDO将是存储条件的变量。

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

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