Search code examples
phpmysqlforeachsql-insertquickbooks-online

Foreach Loop does not insert all records from quickbooks to MySQL database.


I been working on Quickbooks PHP API and I wanted to get data from quickbooks and save in MYSQL using PHP script.

I have successfully connected Quickbooks with PHP and I have done queries to get the data.

  $Products = $ProductsService->query($Context, $realm, "SELECT * FROM item ");
foreach ($Products as $Product)
 {
    //First, we will retrieve the ID, and strip out any spaces/characters.  
    $id = $Product->getId();
    $ProductID = preg_replace("/[^0-9]/","",$id);

    echo('Customer Id=' . $ProductID. '<br>');


    //// test for product name
    if(!empty($Product->getName())){
        $ProductName = $Product->getName();
    } else {
        $ProductName= '';
    }

    //Insert customer into product tables
    $sql = "INSERT INTO products (ProductID__kp, ProductName) 

        VALUES ('".$ProductID."', 
                '".$ProductName."'

                )
                ON DUPLICATE KEY 
                    UPDATE ProductName = '".$ProductName."' ";

    $conn->query($sql);

}

The above script successfully runs and returns result in arrays.

enter image description here

The problems is insert statement. I have 1579 products in quickbooks. But when I run the above script, only 97 records gets saved in MYSQL database.

I'm not sure why it only saves 97 out of 1579.

Thanks in advance.


Solution

  • You actually have two unrelated problems here:

    The QuickBooks Online APIs only return 100 records at a time by default.

    Read the documentation:

    You're only getting back 100 records. You can tell by the size of the array:

    array(100)

    You're ignoring any error checking at all.

    $conn->query($sql);

    Why don't you watch for and catch any errors that happen?

    Then you'd know if a query was failing or not.