I have a little problem and i cant find any results on internet.
My boss have a xml feed from his products provider and he asked me to insert all data from xml link into mysql website db.
So i begin like this:
#database
$sql= new MySQL();
//connect to db
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'dbname';
$sql = mysql_connect ($host, $user, $pass) or die("Error - Unable to Connect");
mysql_select_db($db) or die("Error- Unable to find database");
// specify url of xml file
$url = "thehttpofurlproducts";
// get xml file contents
$xml = simplexml_load_file($url);
foreach ($xml->Items->Item as $item) {
$query = "INSERT INTO products (id,code,info) VALUES ($item->prod_id, $item->prod_code,$item->prod_info)";
$result = mysql_unbuffered_query($query) or die ("Error in query: $query. ".mysql_error());
}
mysql_close($connection);
And there are many others fields he wanted me to import into sql db. He want to make this run in real time so i use cronjobs. But the problem is how to update the products in realtime . When i run this second time it gives me errors like duplicate key, etc.
The xml is like this and its continously update :
<Message>
<EntityType>Products</EntityType>
<Items>
<Item>
<prod_id>235</prod_id>
<prod_code>xzq</prod_code>
<prod_name>Dogs</prod_name>
<prod_info><prod_info/>
<isstoc>false</isstoc>
<UM>UM</UM>
<VAT>20.00</VAT>
<prod_category>Puppies</prod_category>
<prod_subcategory>--</prod_subcategory>
<Onlineprice>0.00</Onlineprice>
<Stock>0.00</Stock>
<Weight/>
</Item>
</Items>
</MESSAGE>
Take a look at MySQL's ON DUPLICATE KEY UPDATE
clause . It'll allow you to update values instead of inserting a new row with the same value.
In your example you could do
...
$query = "INSERT INTO products (id,code,info) VALUES ($item->prod_id, $item->prod_code,$item->prod_info) ON DUPLICATE KEY UPDATE code = $item->prod_code, info = $item->prod_info";
...
I'd also advice you to sanitize your query's parameters before appending them to your query for safety reasons.
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.