【发布时间】:2019-01-04 16:59:48
【问题描述】:
我正在使用 simplexml_load_file 读取 xml 文件。我正在尝试遍历 3 个不同的 xml 文件,然后将值插入 mysql 数据库。它只插入最后一个数组。我应该使用while循环吗?
这是我的代码:
$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();
【问题讨论】:
-
你应该在循环内执行查询,否则你只取数组的最后一个索引,因为 $sql 的内容在每次迭代中都会改变
-
您在每次迭代时覆盖
$sql。您也对 SQL 注入持开放态度。参数化。 -
@Osakr duh!非常感谢!
-
@user3783243 感谢您的反馈!我会调查的。
-
使用准备好的语句也会提高多次插入的性能。在循环之前准备一次,然后绑定值并在循环内执行。