I have a XML data feed which is here.
I am trying to use this function to insert all of the products into a database or update on duplicate key. The duplicate key is the ID on the product element <prod id="685814171" in_stock="yes" stock_quantity="">
. I am saving this as the SKU field.
Here is the function
function parse_xml(){
global $wpdb;
$xml = simplexml_load_file('http://www.hot-offers.net/wp-content/themes/hotoffers/datafeed_249713.xml');
foreach($xml->datafeed->prod as $item){
$att = $item->attributes();
$sql = 'INSERT INTO wp_pcu_babytoddler_products
(sku, title, url, stock_message, price, image, pid)
VALUES
(%d, %s, %s, %s, %d, %s, %s)
ON DUPLICATE KEY UPDATE
title = VALUES(title),
url = VALUES(url),
stock_message = VALUES(stock_message),
price = VALUES(price),
image = VALUES(image),
pid = VALUES(pid);';
$sql_prep = $wpdb->prepare($sql,
(string)$att->id,
(string)$item->text->name,
(string)$item->uri->awTrack,
(string)$att->in_stock,
str_replace('.','',(string)$item->price->buynow),
(string)$item->uri->mImage,
(string)$item->pId);
$wpdb->query($sql_prep);
}
}
And here is my database schema
CREATE TABLE IF NOT EXISTS `wp_pcu_babytoddler_products` (
`sku` int(11) NOT NULL,
`title` text NOT NULL,
`url` text NOT NULL,
`stock_message` text NOT NULL,
`price` int(11) NOT NULL,
`image` text NOT NULL,
`pid` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `wp_pcu_babytoddler_products` ADD PRIMARY KEY (`sku`);
This function is partly working as it inserts 136 rows into the databate but there should be 232 as there are in the feed. What am i doing wrong?
I dont have to use the $wpdb
object to insert these, i just thought it was easier.
EDIT
Here is an error i'm getting although the ID 2147483647 doesn't exist in the XML feed, this appears to be effecting the remaining products.
WordPress database error: [Duplicate entry '2147483647' for key 'sku']
INSERT INTO `wp_pcu_babytoddler_products`
(`sku`, `title`, `url`, `stock_message`, `price`, `image`, `pid`)
VALUES
(
'3083667637',
'Baby Dan BabyDen Play Pen Black 2014',
'http://www.awin1.com/pclick.php?p=3083667637&a=249713&m=3975',
'In Stock',
'9849',
'http://www.babyandtoddlerworld.co.uk/imagprod/imaglarg/BDAN-Babyden-Black.jpg',
'BDAN-Babyden-Black-67116-2600-1400-10'
)
Array
(
[sku] => 3083667637
[title] => Baby Dan BabyDen Play Pen Black 2014
[url] => http://www.awin1.com/pclick.php?p=3083667637&a=249713&m=3975
[stock_message] => In Stock
[price] => 9849
[image] => http://www.babyandtoddlerworld.co.uk/imagprod/imaglarg/BDAN-Babyden-Black.jpg
[pid] => BDAN-Babyden-Black-67116-2600-1400-10
)
Just found the issue, it is with the SKU as an int()
in the database, the maximum number an int()
can store is 2147483647. It truncates any number above that!
I followed this answer: https://stackoverflow.com/a/20442152/1838483
You just need to change the int()
to be varchar(20)
.