我正在阅读sqlsrv_execute
文档,发现了有趣的"示例#1",它展示了如何多次重新执行语句。
我的问题是,我有超过2个参数在我的查询。如何将它们传递到sqlsrv_execute
循环?
文档中的例子就是这样,一个例子。它向您展示了如何可以循环通过一个数组的键值对,并将它们作为单独的行插入到数据库中;但这并不意味着这是唯一的方法。
让我们用几个参数做一个简单的例子:
假设我们正在将客户详细信息的多个条目导入数据库,其中包括:name
, gender
, dob
和address
。通常我们会通过POST
或GET
请求从<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
。