简体   繁体   English

MySQL从foreach结果插入变量

[英]mysql insert variables from foreach results

Cant insert the results generated from foreach loop into mysql database. 无法将从foreach循环生成的结果插入到mysql数据库中。 Im provided with xml file which contains few of the details which will help me generate next generation of url's to access detailed product xml files. 我提供的xml文件包含一些细节,这将帮助我生成下一代url以访问详细的产品xml文件。 Im still in the begging. 我仍然在乞求。 Here is my code: 这是我的代码:

<?php
$xml=simplexml_load_file("http://www.website.com/categories/xml/list.xml") or die("Error: Cannot create object");
foreach ($xml->product as $product)
{
$sql = "INSERT INTO Software (groupId,codeId)
VALUES ('$product->attributes()->groupId,$product->attributes()->codeId')";
if ($conn->query($sql) === TRUE) {
echo "info added successfully";
} else {
echo "Error inserting into table: " . $conn->error;
}
}
$conn->close(); ?>

Here is the error message that i get : 这是我收到的错误消息:

Error creating table: Column count doesn't match value count at row 1 创建表时出错:列数与第1行的值数不匹配
Error creating table: Column count doesn't match value count at row 1 创建表时出错:列数与第1行的值数不匹配
Error creating table: Column count doesn't match value count at row 1 创建表时出错:列数与第1行的值数不匹配

Im not sure if my syntax is wrong or i have to somehow generate specific value for each result. 我不确定我的语法是否错误,或者我必须以某种方式为每个结果生成特定的值。

Thanks in advance for your answers. 预先感谢您的回答。

You only have one large string, but should have two. 您只有一个大字符串,但应该有两个。 Try: 尝试:

$sql = "INSERT INTO Software (groupId,codeId)
VALUES ('$product->attributes()->groupId','$product->attributes()->codeId')";

A better approach would be parameterized. 一个更好的方法将被参数化。

$sql = "INSERT INTO Software (groupId,codeId)
VALUES (?, ?)";

Much easier to read, and safer. 更容易阅读,也更安全。 You then just need to bind the variables $product->attributes()->groupId and $product->attributes()->codeId . 然后,您只需要绑定变量$product->attributes()->groupId$product->attributes()->codeId

Here's a rough example, (the i s are for integers, if strings change to s s. One letter per variable): 这是一个粗略的示例(如果字符串更改为s ,则i代表整数。每个变量一个字母):

$stmt = $conn->prepare($sql)
$stmt->bind_param('ii', $product->attributes()->groupId, $product->attributes()->codeId);
$stmt->execute();

You can read more here, http://php.net/manual/en/mysqli.quickstart.prepared-statements.php . 您可以在http://php.net/manual/en/mysqli.quickstart.prepared-statements.php上阅读更多内容。

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

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