PHP sqlsrv_execute 多次重新执行准备好的语句

PHP sqlsrv_execute re-execute a prepared statement several times

我正在阅读 sqlsrv_execute documentation 并发现有趣的 "Example #1",它显示了如何多次重新执行语句。

我的问题是我的查询中有两个以上的参数。如何将它们传递给 sqlsrv_execute 循环?

文档中的例子只是,一个例子。它向您展示了如何可以 遍历具有键值对的数组并将它们作为单独的行插入到数据库中;但这并不意味着这是唯一的方法。

让我们用几个参数做一个简单的例子:


假设我们要将客户详细信息的多个条目导入到我们的数据库中,其中包括: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()returns一个boolean结果,判断查询是否成功。要访问资源,您将使用 $stmt.