sql update multiple column in a foreach loop using prepared statement - php

Im studying this PHP script on how to prepare for multiple execution of a UPDATE statement. The script below shows update for 1 column using prepared statement.
Example from PHP manual https://www.php.net/manual/en/function.sqlsrv-prepare.php
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);
// Execute the statement for each order.
foreach( $orders as $id => $qty) {
// Because $id and $qty are bound to $stmt1, their updated
// values are used with each execution of the statement.
if( sqlsrv_execute( $stmt ) === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
?>
What if I have multiple column to update, how do I create an array to bound multiple variables to a prepared statement in foreach?
New update SQL statement with 3 columns.
$sql = "UPDATE Table_1
SET OrderQty = ?,
SET ProductName = ?,
SET ProductPRice = ?
WHERE SalesOrderID = ?";

You may try to build the array with the actual parameters values differently. And fix the syntax of the UPDATE statement:
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array("Database" => "dbName", "UID" => "username", "PWD" => "password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if ($conn === false) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "
UPDATE Table_1
SET OrderQty = ?, ProductName = ?, ProductPrice = ?
WHERE SalesOrderID = ?
";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $name = ""; $price = 0.00; $id = 0;
$stmt = sqlsrv_prepare($conn, $sql, array(&$qty, &$name, &$price, &$id));
if ($stmt === false) {
die( print_r( sqlsrv_errors(), true));
}
// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array(
array("qty" => 10, "name" => "Product1", "price" => 10.01, "id" => 1),
array("qty" => 20, "name" => "Product2", "price" => 10.02, "id" => 2),
array("qty" => 30, "name" => "Product3", "price" => 10.03, "id" => 3)
);
// Execute the statement for each order.
foreach ($orders as $order) {
// Because $id and $qty are bound to $stmt1, their updated
// values are used with each execution of the statement.
$qty = $order["qty"];
$name = $order["name"];
$price = $order["price"];
$id = $order["id"];
if (sqlsrv_execute($stmt) === false) {
die( print_r( sqlsrv_errors(), true));
}
}
// End
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>

Related

sqlsrv_fetch_object returns String data, right truncation

I am using a select query to get data with PHP from MSSQL database. But when I am using sqlsrv_fetch_object I get the error: String data, right truncation. Its just a select query from a view, why I receive this message?
Here is my code:
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>$databaseName);
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$tsql = "SELECT custCode, custName, comments, incharge, currency, country, sellerID, sellerName, paymentMethod, category, dispatchMethod FROM [DataBase-Name].[dbo].[eshopCustomers]";
$stmt = sqlsrv_query($conn, $tsql,[],[ "Scrollable" => SQLSRV_CURSOR_KEYSET ]);
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
//number of results
$num = sqlsrv_num_rows($stmt);
//if user is not in latest update then make him inactive
$current_user_ids = [];
if( $num > 0 ){
for($i = 0; $i < $num; $i++){
$cst = sqlsrv_fetch_object($stmt); print_r($cst);
if( $cst === false ) {
die( print_r( sqlsrv_errors(), true));
} die();
...............................................................

No data from Database

I wrote an php application which should select data from the database depending on a given date. The date in the Database is stored like 2020-07-03. The code which executes the statement looks like
$from = $_POST['from'];
$to = $_POST['to'];
$sql = "SELECT * FROM Database WHERE Date < $from";
$stmt = sqlsrv_query($conn, $sql);
if($stmt == false){
die( print_r( sqlsrv_errors(), true) );
}
echo $sql;
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
echo $row[0].", ".$row[1]."<br />";
}
$from and $to is a range which is given by the user with date-input fields and return the userinput like 2020-07-02. The datatype of the field "Date" is Date. I do not get any error or something similar but it won't execute the while loop and I can't figure out why.
You need to use parameters in your statement. As is mentioned in the documentation, sqlsrv_query() function is well-suited for one-time queries and should be the default choice to execute queries unless special circumstances apply. This function provides a streamlined method to execute a query with a minimum amount of code. The sqlsrv_query function does both statement preparation and statement execution, and can be used to execute parameterized queries.
You need to pass the values of parameters in one of the following ways:
As text using an unambiguous date format (yyyymmdd),
Using extended parameters syntax and the appropriate data type bindings.
Example, based on the code in the question, using text values for dates:
<?php
// Connection
$server = 'server,port';
$database = 'database';
$uid = 'uid';
$pwd = 'pwd';
$cinfo = array(
"ReturnDatesAsStrings" => true,
"Database" => $database,
"UID" => $uid,
"PWD" => $pwd
);
$conn = sqlsrv_connect($server, $cinfo);
if ($conn === false) {
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
// Test input
$from = (new DateTime('2020-07-02'))->format('Ymd');
$to = (new DateTime('2020-07-03'))->format('Ymd');
// Statement
$sql = "
SELECT *
FROM Database
WHERE (? <= [Date]) AND ([Date] <= ?)"
;
$params = array($from, $to);
$stmt = sqlsrv_query($conn, $sql, $params);
if($stmt == false){
die( print_r( sqlsrv_errors(), true) );
}
echo $sql;
// Data
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
echo $row[0].", ".$row[1]."<br />";
}
// End
sqlsrv_free_stmt($stmt);
?>
Example, based on the code in the question, using PHP date objects and the appropriate parameters bindings:
<?php
// Connection
$server = 'server,port';
$database = 'database';
$uid = 'uid';
$pwd = 'pwd';
$cinfo = array(
"ReturnDatesAsStrings" => true,
"Database" => $database,
"UID" => $uid,
"PWD" => $pwd
);
$conn = sqlsrv_connect($server, $cinfo);
if ($conn === false) {
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
// Test input
$from = new DateTime('2020-07-02');
$to = new DateTime('2020-07-03');
// Statement
$sql = "
SELECT *
FROM Database
WHERE (CONVERT(date, ?) <= [Date]) AND ([Date] <= CONVERT(date, ?))"
;
$params = array(
array($from, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_DATETIME, SQLSRV_SQLTYPE_DATETIME),
array($to, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_DATETIME, SQLSRV_SQLTYPE_DATETIME)
);
$stmt = sqlsrv_query($conn, $sql, $params);
if($stmt == false){
die( print_r( sqlsrv_errors(), true) );
}
echo $sql;
// Data
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
echo $row[0].", ".$row[1]."<br />";
}
// End
sqlsrv_free_stmt($stmt);
?>

Parameterized Query PHP/SQL Server

I have a web form that enters event details into a database to be listed on a website. The form captures the name of a photo, event title, a date to unlist the event, a sort number, a description, and a bit flag "Mass".
The description field is a plain text field. I know that I should probably change the field to rich text, but that is for a day when I have time to explore how to do that. Anyways... I've been adding HTML characters into my text to format it. I find that the slash of closing characters like < / strong> is being treated as an escape character rather than part of the text. How do I tell my code to not escape?
The code:
//connect to the database.
$serverName = "livedata";
$connectionInfo = array( "Database"=>"administration", "UID"=>"User", "PWD"=>"PASSWORD", "LoginTimeout"=>60 );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
/* Set up the parameterized query. */
$tsql = "insert into tblevents (Photo, title, Unlist, Sort, Description, Par_num, mass ) values(?,?,?,?,?,?,?)";
/* Set parameter values. */
$dt = $_POST['unlist'];
if ($dt == ""){
$dt = null;
}
$Sort = $_POST['sort'];
if ($Sort == "" ){
//query to get the max of sort in the database items
//+1 sort
$sql2 = "SELECT tblevents.Par_Num, Max(tblevents.Sort) AS MaxOfSort FROM parishevents.dbo.tblevents GROUP BY tblevents.Par_Num HAVING (((tblevents.Par_Num)=" . $_POST['par_num'] . "));";
//echo "SQL2: " . $sql2 . "<br><br>";
$stmt2 = sqlsrv_query( $conn, $sql2);
if( $stmt2 === false ) {
die( print_r( sqlsrv_errors(), true));
}
$result2 = sqlsrv_query($conn, $sql2);
while($row2 = sqlsrv_fetch_array($result2)) {
$Sort = $row2['MaxOfSort'] +1;
}
if(isset($_POST['mass'])){
if($_POST['mass'] == "on"){
$mass = -1;
}
else{
$mass = 0;
}
}else{
$mass = 0;
}
$params = array($_POST['photo'], $_POST['title'], $dt, $Sort, $_POST['description'], $_POST['par_num'], $mass);
/* Prepare and execute the query. */
$stmt = sqlsrv_query($conn, $tsql, $params);
/* Free statement and connection resources. */
sqlsrv_free_stmt($stmt);
}

how to bind parameters in sqlsrv without using of PDO

In MySQL we used the mysqli_stmt_bind_param to bind parameters.
What should I use to bind parameters in sqlsrv?
$sql = "SELECT * FROM dbo.[user] WHERE username = ? and password = ?";
$stmt = sqlsrv_prepare($conn, $sql, $params);
if($stmt === false){
die( print_r( sqlsrv_errors(), true));
}
How can I bind this parameters? This is a php file and I need to bind them without pdo.
You don't explicitly bind the parameters by using another function, you do it when preparing the statement.
See the example from the manual.
$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";
// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);
// Execute the statement for each order.
foreach( $orders as $id => $qty) {
// Because $id and $qty are bound to $stmt1, their updated
// values are used with each execution of the statement.
if( sqlsrv_execute( $stmt ) === false ) {
die( print_r( sqlsrv_errors(), true));
}
}

PHP database rollback with MSSQL

I am new in the MSSQL. i have create a database in MSSQL. Now all is working fine like add/edit/delete. i am adding 3 record in 3 different table at the same time in same of different database.
I want to use Rollback in the database.
Suppose i am adding three record at the same time. First two work properly and last query find some issue in adding it in the table. At this time i want to remove the first two query which is inserted in the table.
can anyone help me for this issue ?
if you have another option to solve this issue then let me know
Thanks in advance
Use sqlsrv_begin_transaction() function to begin a transaction. Then, you can either commit it by calling sqlsrv_commit() function or roll it back by calling sqlsrv_rollback() function.
Example from php.net manual
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;
/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );
/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>

Categories