2016-10-25 32 views

回答

1

該文檔中的示例就是示例。它向您展示瞭如何通過具有鍵值對的數組循環遍歷數組,並將它們作爲單獨的行插入到數據庫中;但這並不意味着這是做到這一點的唯一方法。

讓我們做一些參數一個簡單的例子:


比方說,我們正在導入到我們的數據庫的客戶詳細信息的多個條目,其中包括:namegenderdobaddress。通常我們會通過POSTGET請求以<form>的數組形式獲取這些數據。因此,例如,我們可以有以下陣列:

// Names    // Genders  // DoB      // Address 
Array (    Array (   Array (     Array (
    [0] => "Bob"   [0] => "M"  [0] => "25/04/1994"  [0] => "123 Somewhere Lane" 
    [1] => "Tim"   [1] => "M"  [1] => "02/12/1986"  [1] => "456 Somewhere Lane" 
    [2] => "Jane"  [2] => "F"  [2] => "29/06/2001"  [2] => "789 Somewhere Lane" 
)     )    )       ) 

現在讓我們來創建我們事先準備好的聲明:

//We've already got a connection created 

$query = "INSERT INTO [customers].[cust_details] 
      ([name], [gender], [DoB], [address]) 
      VALUES (?,?,?,?)"; 

$stmt = sqlsrv_prepare($conn, $query, array(&$name, &$gender, &$dob, &$address)); 

變量$name$gender$dob$address現在綁定到本聲明。

現在讓我們創建一個循環來執行查詢多次:

// I used a for loop here as an example 
// but choose whatever loop is suitable for what you need to achieve 

for($i = 0; $i < count($namesArray); $i++) { 
    // Each iteration will store a different value into these variables 
    // These variables are bound to $stmt, therefore whatever is stored 
    // at the time of sqlsrv_execute() is sent as the parameters 
    $name = $namesArray[$i]; 
    $gender = $gendersArray[$i]; 
    $dob  = $dobsArray[$i]; 
    $address = $addressesArray[$i]; 

    // Execute the statement 
    if(sqlsrv_execute($stmt) === false) { 
     // there has been an error 
     die(print_r(sqlsrv_errors(), true)); 
    } 
} 

注:sqlsrv_execute()返回boolean結果,該查詢是否成功與否。要訪問資源,您可以使用$stmt