I was reading sqlsrv_execute
documentation and found the interesting "Example #1" which shows how to re-execute a statement several times.
My problem is that I have more than 2 parameters in my query. How do I pass them to the sqlsrv_execute
cycle?
The example in the documentation is just that, an example . It is showing you how you could loop through an array that has key-value pairs and insert them as individual rows into the database; but it doesn't mean that it is the only way to do it.
Let's do a simple example with a few parameters:
Let's say we are importing into our database multiple entries of customer details which include: name
, gender
, dob
and address
. Typically we would get these in array form from a <form>
through either a POST
or GET
request. So, for example, we could have the following arrays:
// 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"
) ) ) )
Now lets create our prepared statement:
//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));
The variables $name
, $gender
, $dob
and $address
are now bound to this statement.
Now let's create a loop to execute the query multiple times:
// 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));
}
}
Note: sqlsrv_execute()
returns a boolean
result as to whether the query was successful or not. To access the resource you would use $stmt
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.