如何使用PHP将多个XML价格插入到SQL表中

时间:2017-01-13 15:36:09

标签: php mysql xml

我一直试图找到以下问题的答案,但似乎无法找到解决方案。我已经能够在我的SQL表中插入一个产品价格,但我尝试多种产品的所有可能性都无效。这是我的一个产品的工作代码。

<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>

<body>

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

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

$xml=simplexml_load_file("URL") or die("Error: Cannot create object");

foreach ($xml->product as $row) {
    $price = $row -> price;

$sql = "INSERT INTO `tablename` (`price`) 
        VALUES ('$price')"; 

}

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

$conn->close();
?>


</body>
</html>

我应该添加或更改哪些内容以使查询遍历整个XML文件并查找产品的所有价格?

提前致谢!

1 个答案:

答案 0 :(得分:0)

您可以使用 mysqli :: multi_query 来完成。只将分号放在sql的末尾并使用multi_query执行:

$sql = "";


foreach ($xml->product as $row) {

    $price = $row -> price;

    $sql .= "INSERT INTO `product` (`price`)
        VALUES ('$price');";

}


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