简体   繁体   中英

mysql insert variables from foreach results

Cant insert the results generated from foreach loop into mysql database. 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. 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
Error creating table: Column count doesn't match value count at row 1
Error creating table: Column count doesn't match value count at row 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 .

Here's a rough example, (the i s are for integers, if strings change to s s. One letter per variable):

$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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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