2016-10-25 3 views

答えて

1

ドキュメントの例は、の例です。 はどのようにしてのキーと値のペアを持つ配列をループし、個々の行としてデータベースに挿入するかを示しています。それがそれを行う唯一の方法であるということではありません。

のは、いくつかのパラメータを簡単な例をやってみましょう:namegenderdobaddress


は我々が含ま顧客の詳細情報を当社のデータベースに複数のエントリにインポートされているとしましょう。通常、<form>からPOSTまたはGETのいずれかのリクエストを使用して、これらを配列形式で取得します。ですから、例えば、私たちは次の配列を持つことができます:

//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は今、この文にバインドされています

// 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" 
)     )    )       ) 

は今私達のプリペアドステートメントを作成することができます。

今度は、クエリを複数回実行するループを作成してみましょう:

// 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を使用します。

関連する問題