私はsqlsrv_execute
documentationを読んでいましたが、何度もステートメントを再実行する方法を示す興味深い "Example#1"が見つかりました。PHP sqlsrv_executeは何度もプリペアドステートメントを再実行します
私の問題は、クエリに2つ以上のパラメータがあることです。 sqlsrv_execute
サイクルにそれらを渡すにはどうすればよいですか?
私はsqlsrv_execute
documentationを読んでいましたが、何度もステートメントを再実行する方法を示す興味深い "Example#1"が見つかりました。PHP sqlsrv_executeは何度もプリペアドステートメントを再実行します
私の問題は、クエリに2つ以上のパラメータがあることです。 sqlsrv_execute
サイクルにそれらを渡すにはどうすればよいですか?
ドキュメントの例は、の例です。 はどのようにしてのキーと値のペアを持つ配列をループし、個々の行としてデータベースに挿入するかを示しています。それがそれを行う唯一の方法であるということではありません。
のは、いくつかのパラメータを簡単な例をやってみましょう:name
、gender
、dob
とaddress
:
は我々が含ま顧客の詳細情報を当社のデータベースに複数のエントリにインポートされているとしましょう。通常、<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
を使用します。