How can I update the products varients stock using the php?

How can I update the products varients stock using the php?

Pankajbachhal
Shopify Partner
2 0 0

Hey Guys,
Please help me out I'm stuck !!!


I have created a shopify app for updating the stock of the products. It is updating the stock but it is not updating the varients stock. Can some help me with this code I'm not getting whats worng with it.

  if(isset($_REQUEST['stockupdate'])){
        $start = 0;
        $queuestart = 50;

        $sqlb = "SELECT pending_num FROM stock_queue where id = '1'";
        $resultb = mysqli_query($conn, $sqlb);
        $rowb = mysqli_fetch_assoc($resultb);
        $queuestart = $rowb['pending_num'];

        echo 'Please Wait Stock Update In Process... '.$queuestart.' -- <br><br>';
       
       
        $sqla = "SELECT count(*) FROM csv_new";
        $resulta = mysqli_query($conn, $sqla);
        $rowa = mysqli_fetch_assoc($resulta);
        $totaldataindb = $rowa['count(*)'];
       
        if($queuestart<$totaldataindb){
           
            $start = $queuestart;
            $queuestart+=50;
            $qrupdate = "UPDATE stock_queue set pending_num='".$queuestart."' WHERE id ='1'";
            mysqli_query($conn, $qrupdate);
            $sqlorder = "SELECT * FROM csv_new where id between $start and $queuestart";
         
            $resultorder = mysqli_query($conn, $sqlorder);

            if (mysqli_num_rows($resultorder) > 0) {
                   
                    while($roworder = mysqli_fetch_assoc($resultorder)) {
 
                        if($roworder['product_name_in_csv']!='' && $roworder['product_name_in_csv']!='eancode'){
                            $query = array('query'=>'{
                                products(first:1, query:"sku:'.$roworder['product_name_in_csv'].'") {
                                    edges {
                                        node {
                                                id
                                                title
                                                variants(first:20){
                                                    edges{
                                                      node{
                                                        title
                                                        inventoryItem{
                                                          id
                                                        }
                                                      }
                                                    }
                                                  }
                                            }
                                        }
                                    }
                                }
                            ');
  $subscription = shopify_gql_call($token, $shp3, $query);
  $subscriptionres = json_decode($subscription['response'], JSON_PRETTY_PRINT);
  foreach ($subscriptionres as $subscriptionval) {
   foreach ($subscriptionval['products']['edges'] as $keysub => $valuesub) {
    foreach ($valuesub['node']['variants']['edges'] as $key1 => $value1) {
     if($roworder['stock_variants']==$value1['node']['title'] || $value1['node']['title']=='Default Title'){
           $getinventroyid = str_replace("gid://shopify/InventoryItem/","",$value1['node']['inventoryItem']['id']);
            $inlvl_array2 = array('inventory_item_ids'=>$getinventroyid);
           $inlvlTag2 = shopify_call($token, $shp3, "/admin/api/2021-07/inventory_levels.json", $inlvl_array2,'GET');
           $inlvlTag2 = json_decode($inlvlTag2['response'], JSON_PRETTY_PRINT);
                                           
         $inlvl_array = array(
             "location_id" => $inlvlTag2['inventory_levels'][0]['location_id'],
             "inventory_item_id" => $inlvlTag2['inventory_levels'][0]['inventory_item_id'],
              "available" => $roworder['new_stock_csv']
         );
 $inlvlTag = shopify_call($token, $shp3, "/admin/api/2022-07/inventory_levels/set.json", $inlvl_array,'POST');
 $inlvlTag = json_decode($inlvlTag['response'], JSON_PRETTY_PRINT);
}
 }
}
 }
  }
}
 
                } else {
                    echo "0 results";
                }

               
            ?>
            <script>
             window.location.reload();
            </script>
            <?php
               
        }
        echo "Process Completed!! <br> <br> <br> <button class='updatestockbtn' id='btnbackhome'>Back to home page</button>";
   
    }

    

Pankaj
Replies 3 (3)

okur90
Shopify Partner
126 20 18

Hey @Pankajbachhal 

I've tweaked your code a bit to make sure the inventory levels for each variant get updated properly. Check out the changes.

 

if (isset($_REQUEST['stockupdate'])) {
    $start = 0;
    $queuestart = 50;

    $sqlb = "SELECT pending_num FROM stock_queue where id = '1'";
    $resultb = mysqli_query($conn, $sqlb);
    $rowb = mysqli_fetch_assoc($resultb);
    $queuestart = $rowb['pending_num'];

    echo 'Please Wait Stock Update In Process... ' . $queuestart . ' -- <br><br>';

    $sqla = "SELECT count(*) FROM csv_new";
    $resulta = mysqli_query($conn, $sqla);
    $rowa = mysqli_fetch_assoc($resulta);
    $totaldataindb = $rowa['count(*)'];

    if ($queuestart < $totaldataindb) {

        $start = $queuestart;
        $queuestart += 50;
        $qrupdate = "UPDATE stock_queue set pending_num='" . $queuestart . "' WHERE id ='1'";
        mysqli_query($conn, $qrupdate);
        $sqlorder = "SELECT * FROM csv_new where id between $start and $queuestart";

        $resultorder = mysqli_query($conn, $sqlorder);

        if (mysqli_num_rows($resultorder) > 0) {

            while ($roworder = mysqli_fetch_assoc($resultorder)) {

                if ($roworder['product_name_in_csv'] != '' && $roworder['product_name_in_csv'] != 'eancode') {
                    $query = array('query' => '{
                                products(first:1, query:"sku:' . $roworder['product_name_in_csv'] . '") {
                                    edges {
                                        node {
                                                id
                                                title
                                                variants(first:20){
                                                    edges{
                                                      node{
                                                        title
                                                        inventoryItem{
                                                          id
                                                        }
                                                      }
                                                    }
                                                  }
                                            }
                                        }
                                    }
                                }
                            ');
                    $subscription = shopify_gql_call($token, $shp3, $query);
                    $subscriptionres = json_decode($subscription['response'], JSON_PRETTY_PRINT);

                    // Loop through each product variant
                    foreach ($subscriptionres as $subscriptionval) {
                        foreach ($subscriptionval['products']['edges'] as $keysub => $valuesub) {
                            foreach ($valuesub['node']['variants']['edges'] as $key1 => $value1) {

                                // Update the inventory level for the current variant
                                $getinventroyid = str_replace("gid://shopify/InventoryItem/", "", $value1['node']['inventoryItem']['id']);
                                $inlvl_array2 = array('inventory_item_ids' => $getinventroyid);
                                $inlvlTag2 = shopify_call($token, $shp3, "/admin/api/2021-07/inventory_levels.json", $inlvl_array2, 'GET');
                                $inlvlTag2 = json_decode($inlvlTag2['response'], JSON_PRETTY_PRINT);

                                // Check if the current variant title matches the stock_variants or if it's the default title
                                if ($roworder['stock_variants'] == $value1['node']['title'] || $value1['node']['title'] == 'Default Title') {
                                    // Set the new stock level for the current variant
                                    $inlvl_array = array(
                                        "location_id" => $inlvlTag2['inventory_levels'][0]['location_id'],
                                        "inventory_item_id" => $inlvlTag2['inventory_levels'][0]['inventory_item_id'],
                                        "available" => $roworder['new_stock_csv']
                                    );
                                    $inlvlTag = shopify_call($token, $shp3, "/admin/api/2022-07/inventory_levels/set.json", $inlvl_array, 'POST');
                                    $inlvlTag = json_decode($inlvlTag['response'], JSON_PRETTY_PRINT);
                                }
                            }
                        }
                    }
                }
            }
        } else {
            echo "0 results";
        }
        ?>
        <script>
            window.location.reload();
        </script>
        <?php
    }
    echo "Process Completed!! <br> <br> <br> <button class='updatestockbtn' id='btnbackhome'>Back to home page</button>";
}

 

I made a little change to your code by adding a condition to double-check whether the current variant title matches the stock_variants or if it has the default title. By doing this, we can make sure that the inventory levels are updated for the right variants.

Code Slingin, Pixel Wranglin - Laugh it up at onlinex.com.au
Pankajbachhal
Shopify Partner
2 0 0

Hi @okur90 ,

Thanks For your reply Still it is not updating the variant stocks

Pankajbachhal_0-1682429952572.png


Thanks
Pankaj

Pankaj
okur90
Shopify Partner
126 20 18

You can try adding some log statements in the loop where the inventory levels are being updated. This can help you identify if there's a problem with the data being fetched or the API calls being made.

 

// ...
// Check if the current variant title matches the stock_variants or if it's the default title
if ($roworder['stock_variants'] == $value1['node']['title'] || $value1['node']['title'] == 'Default Title') {
    // Log the matched variant title and inventory level
    echo "Updating inventory for variant title: " . $value1['node']['title'] . " - New stock level: " . $roworder['new_stock_csv'] . "<br>";

    // Set the new stock level for the current variant
    // ... (rest of the code)
} else {
    // Log the unmatched variant title
    echo "Unmatched variant title: " . $value1['node']['title'] . "<br>";
}

 

Code Slingin, Pixel Wranglin - Laugh it up at onlinex.com.au