2016-10-27 58 views
1

我連接到一個跟蹤客戶訂單的API。一些訂單有一個產品,但一些訂單有一個訂單有多個產品。當我嘗試並插入到我的數據庫中時,我只能得到第一個產品。我希望將所有產品插入其中不止一個的情況下。產品名稱的API的XML是 - > orderItems-> orderItem-> productName,我試圖遍歷所有這些,但我仍然只獲得第一個產品。從API中插入多個值到mysql數據庫中

foreach ($customer_orders as $customer_order) 
{ 
       $chOrder = curl_init('https://'. $customer_order->reference); 
       curl_setopt($chOrder, CURLOPT_USERPWD, "username" . ":" . "password"); 
       curl_setopt($chOrder, CURLOPT_HTTPHEADER, array('Content-Type: application/xml')); 
       curl_setopt($chOrder, CURLOPT_RETURNTRANSFER, true); 
       $orderResult = curl_exec($chOrder); 
       curl_close($chOrder); 

       $shouldContinue = true; 
       try 
       { 
        $singleXML = new SimpleXMLElement($orderResult); 
       } 
       catch (Exception $e) 
       { 
        $shouldContinue = false; 
        error_log($e); 
        error_log('Failed to get history for ' . wp_get_current_user()->user_email . ' using refernece: ' . $customer_order->reference); 
       } 

       if ($shouldContinue) 
       { 

        ++$orderCount; 


        foreach ($singleXML->orderItems->orderItem as $item) { 
         $product = htmlentities($item->productName, ENT_QUOTES, 'UTF-8'); 
        } 


        $con = mysqli_connect('localhost','root','password','database'); 

        $query = "INSERT IGNORE INTO customer_product_list(`product`)VALUES('$product')"; 

        mysqli_query($con,$query); 

        mysqli_close($con); 

     } 

} 

回答

0
try put insert query inside foreach loop 
$con = mysqli_connect('localhost','root','password','database'); 
foreach ($singleXML->orderItems->orderItem as $item) { 
$product = htmlentities($item->productName, ENT_QUOTES, 'UTF-8'); 
$query = "INSERT IGNORE INTO  

customer_product_list(`product`)VALUES('$product')"; 

mysqli_query($con,$query); 


} 
mysqli_close($con); 
+0

我嘗試過了,這是不是解決辦法。 – Eseye

+0

actualy每次產品被替換爲新的,最後最後一個oroduct將被插入db –

+0

那麼我怎樣才能讓它們都在那裏? – Eseye