我正在使用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();
答案 0 :(得分:1)
每次在foreach中进行迭代时,都会覆盖$ sql变量。由于您是在for循环之后执行查询,因此仅将数组的最后一项插入数据库。
要解决此问题,您应该将查询放入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;
}
}
但是您必须小心使用SQL Injection,我建议您看一下PDO。 http://php.net/manual/en/ref.pdo-mysql.php
让我将其转换为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 将是存储conexion的变量。