There are times when we either need to inspect the shopify data all at once or create some external dashboard to list shopify product outside of shopify. At that time we need to extract all products from shopify and store somewhere else on database.
This article will guide you though how to execute a single file and get all your shopify products on your external database. In my case i’m storing on local machine xampp server’s mysql.
The first thing is i will be using this private app skeleton https://github.com/phpish/shopify_private_app-skeleton
Below are few of the major things that are taken care on the code block below.
- Connect to database to collect products data
- Make use of shopify product api reference
- Shopify limits to fetch to 50 products at once and 250 at max but we are looping the request to fetch all products at once, this is bit tricky.
- The global variables shopify api key, app password are configured on conf.php from private app skeleton
- I’m just extracting product id, product title and handle. You can access more data.
- Cheers !!
session_start(); require __DIR__.'/vendor/autoload.php'; use phpish\shopify; require __DIR__.'/conf.php'; //Connection to Database to store database $servername = "localhost"; $username = "root"; $password = ""; $database = '{{YOUR-DATABASE-NAME}}'; $db = new mysqli($servername, $username, $password,$database); if ($db->connect_error) { die("Connection failed: " . $db->connect_error); } $shopify = shopify\client(SHOPIFY_SHOP, SHOPIFY_APP_API_KEY, SHOPIFY_APP_PASSWORD, true); try { # Making an API request can throw an exception $products = $shopify('GET /admin/products/count.json', array('published_status'=>'published')); $totalproducts = $shopify('GET /admin/products/count.json', array('published_status'=>'published')); $limit = 50; $totalpage = ceil($totalproducts/$limit); // Shopify limits to fetch to 50 at once and 250 at max but we are looping request to fetch all at once for($i=1; $i<=$totalpage; $i++){ $products = $shopify('GET /admin/products.json?limit='.$limit.'&page='.$i, array('published_status'=>'published')); foreach($products as $product){ $product = (object)$product; $productid = $product->id; $title = mysqli_real_escape_string($db,$product->title); //insert into db table $sqlc = "INSERT INTO `products` (`product_id`,`product_title`,`product_handle`)VALUES ('$productid', '$title','$product->handle')"; if(!$result = $db->query($sqlc)){ die('There was an error running the query [' . $db->error . ']'); } } } } catch (shopify\ApiException $e) { # HTTP status code was >= 400 or response contained the key 'errors' echo $e; print_R($e->getRequest()); print_R($e->getResponse()); } catch (shopify\CurlException $e) { # cURL error echo $e; print_R($e->getRequest()); print_R($e->getResponse()); }
Leave a Reply