i am try to wright some code the code wrights to the data base ok but only one entry shows up i cant seem to get the foreach statment to work it dont loop here is my code
thank you
<?php
ini_set('display_errors','On');
echo "starting";
//mysql connection
$con2 = mysql_connect("localhost","user","pass");
if (!$con2) {
die('Could not connect: ' . mysql_error());
}
$selectdb = mysql_select_db("database", $con2);
if (!$selectdb) {
die('Database not used: ; ' . mysql_error());
}
echo "connected to DB<br /><br />";
//simplexml load xml file
{
$xml = simplexml_load_file('myproduct.xml');
mysql_query('DELETE FROM products WHERE 1');
mysql_query('DELETE FROM categories_description WHERE 1');
mysql_query('DELETE FROM products_to_categories WHERE 1');
}
{
foreach($xml->CREATED->CATEGORY->PRODUCT as $product);
foreach($xml->xpath('//PRODUCT/@ITEM') as $productitemid);
foreach($xml->CREATED->CATEGORY as $categories);
foreach($xml->xpath('//CATEGORY/@id') as $id);
foreach($xml->xpath('//CATEGORY/@name') as $name);
mysql_query("INSERT INTO products (products_model,products_id) VALUES ('$product->MODEL','$productitemid')");
mysql_query("INSERT INTO products_to_categories (products_id,categories_id) VALUES ('$productitemid','$id')");
mysql_query("INSERT INTO categories (categories_id) VALUES ('$id')");
mysql_query("INSERT INTO categories_description (categories_id,categories_name) VALUES ('$id','$name')");
mysql_query("INSERT INTO categories_description (categories_name) VALUES ('$name')");
//echo "$categories\
<br /><br />";
// or die(mysql_error());
echo "inserted into mysql<br /><br />";
//show updated records
printf ("Records inserted: %d\
", mysql_affected_rows());
}
//close connection
mysql_close($con2);
?>
foreach($xml->xpath('//PRODUCT/@ITEM') as $productitemid){
foreach($xml->CREATED->CATEGORY->PRODUCT as $product)
mysql_query("INSERT INTO products (products_id,products_model)
VALUES ('$productitemid','$product->MODEL')");
}
You still have a bad foreach inside a good foreach.
foreach($xml->xpath('//PRODUCT/@ITEM') as $productitemid){
foreach($xml->CREATED->CATEGORY->PRODUCT as $product) {
mysql_query("INSERT INTO products (products_id,products_model)
VALUES ('$productitemid','$product->MODEL')")
}
}
But, are you sure you need to nest two foreach()? To know that I would have to know the structure of the array or arrays you are working with.
If they don’t need to be nested, this might work
foreach($xml->xpath('//PRODUCT/@ITEM') as $productitemid){
mysql_query("INSERT INTO products (products_id,products_model)
VALUES ('$productitemid','$xml->CREATED->CATEGORY->PRODUCT')")
}
Or you might need
foreach($xml->xpath('//PRODUCT/@ITEM') as $key=>$productitemid){
mysql_query("INSERT INTO products (products_id,products_model)
VALUES ('$productitemid',
'$xml->xpath('//PRODUCT/@ITEM')[$key]['something']')")
}