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 />";
}
?>
Related
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();
...............................................................
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);
?>
I tried to call a SQL Server stored procedure from PHP.
Here is my stored procedure:
CREATE procedure [dbo].[tester]
#id NVARCHAR(MAX)
AS
BEGIN
DECLARE #tab TABLE (myxml XML)
INSERT INTO #tab(myxml)
SELECT map
FROM forms
WHERE mapid = #id
SELECT * FROM #tab
END
and my PHP script:
<?php
$serverName = "servername";
$connectionInfo = array("UID" => "sa","PWD" => "mypass","Database" => "database");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if ($conn) {
$tsql = "exec tester 'FORMgRGVL7bfpEnpBpg7vz2sHoKAs5zxU5LW'";
$result = sqlsrv_query($conn, $tsql);
if ($result === false) {
die( print_r( sqlsrv_errors(), true) );
$response=array('response'=>'notok','data'=>'loyo');
$serverresponse=JSON_encode($response);
} else {
$row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_NUMERIC);
$response=array('response'=>'ok','data'=>$row[0]);
$serverresponse=JSON_encode($response);
}
sqlsrv_free_stmt($stmt);
} else {
$response=array('response'=>'notok','flag'=>$flag,'data'=>'cc');
$serverresponse = $serverresponse=JSON_encode($response);
}
echo ($serverresponse);
?>
When I execute the stored procedure from SSMS it returns the value as expected, but when I execute it from PHP, it returns null.
Explanations:
You need to put SET NOCOUNT ON as first line in your stored procedure to prevent returning the number of rows affected by the T-SQL statements as part of the result set. This is the reason for your NULL results.
As a note, always use prepared statements and parameterized queries to prevent SQL injection. With PHP Driver for SQL Server, function sqlsrv_query() does both statement preparation and statement execution and can be used to execute parameterized queries.
Example:
There are errors in your script, which are fixed in the example:
sqlsrv_free_stmt($stmt) is changed to sqlsrv_free_stmt($result)
variable $flag is not defined
$serverresponse = $serverresponse=JSON_encode($response) is changed to $serverresponse = json_encode($response)
T-SQL:
CREATE procedure [dbo].[tester]
#id nvarchar(max)
as
begin
SET NOCOUNT ON
declare #tab table (myxml xml)
insert into #tab(myxml)
select map from forms where mapid=#id
select * from #tab
end
PHP:
<?php
$flag = "";
$serverName = "servername";
$connectionInfo = array("UID" => "sa", "PWD" => "mypass", "Database" => "database");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if ($conn) {
$tsql = "exec tester ?";
$params = array('FORMgRGVL7bfpEnpBpg7vz2sHoKAs5zxU5LW');
$result = sqlsrv_query($conn, $tsql, $params);
if ($result === false) {
die( print_r( sqlsrv_errors(), true) );
$response = array('response'=>'notok', 'data'=>'loyo');
$serverresponse = json_encode($response);
} else {
$row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_NUMERIC);
$response = array('response'=>'ok', 'data'=>$row[0]);
$serverresponse = json_encode($response);
}
sqlsrv_free_stmt($result);
} else {
$response = array('response'=>'notok', 'flag'=>$flag, 'data'=>'cc');
$serverresponse = json_encode($response);
}
echo ($serverresponse);
?>
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);
}
Please note that i tried all existing solutions and still haven't got output.
I have a php page that calls a Stored Procedure in SQL Server using sqlsrv functions. I have tried existing solutions but unable to solve my problem. When i execute this same SP in SQL Management Studio, it gives output of 31 rows. However, here in my code i am unable to get any row of data. Could someone advise on how to?
Here is my code:
$serverName = "(local)"; //serverName\instanceName
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$connectionInfo = array( "Database"=>"TESTDB");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
$AcCode = '18100017';
$StartDate = '2016/12/01';
$EndDate = '2016/12/31';
$CutAmt = -50000;
$IntRate1 = 2;
$IntRate2 = 3;
$sql = "EXEC dbo.uspGetBankInterest #AC_NO= ?, #AsOfDate= ?, #EndDate= ? ,#CutAmt= ?, #IntRate1= ?, #IntRate2= ?";
$stmt = sqlsrv_prepare($conn, $sql, array(&$AcCode,&$StartDate,&$EndDate,&$CutAmt,&$IntRate1,&$IntRate2));
$result=sqlsrv_execute($stmt);
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
if($result){
echo "SP Executed!";
}
$ctr=0;
$row_count = sqlsrv_num_rows( $stmt );
echo ' '.$row_count.'<br>';
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
print_r($stmt);
echo($row['STAT_DATE'].' '.$row['STAT_AMT'].' '.$row['INT_AMT']."<br>");
$ctr++;
}
echo 'The total number of records are:'.$ctr;
die();
}
else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
The output i get is:
SP Executed!
The total number of records are:0
When i executed, there was an output of 31 records and the data was displayed correctly. There is no problem in my SP. However, when i am trying it in php, no data is brought. How can i solve this problem?