Parameterized Query PHP/SQL Server - php

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);
}

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);
?>

Executing stored procedure in php laravel

I am using Laravel 7 and I want to show the results from the stored procedure. My code is given below. When I execute the stored procedure with parameters in SQL Server, it's showing data. But in Laravel application data is not showing.
Please, help me to find the problem.
$serverName = env("DB_HOST");
$connectionInfo = array( "Database"=>env("DB_DATABASE"), "UID"=>env("DB_USERNAME"), "PWD"=>env("DB_PASSWORD") );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$tsql= " EXEC USP_Daily_TA_Punching_Detailswith_OT '$employee','$datefrom','$dateto'";
$getResults= sqlsrv_query($conn, $tsql);
$data = array();
if ($getResults == FALSE)
{
echo '';
}
else {
//$data[] ='';
do
{
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC))
{
$data[] = $row;
}
}
while (sqlsrv_next_result($getResults));
}
if(count($data)>0){
sqlsrv_free_stmt($getResults);
$total_row = count($data);
}
Always try to use parameters in your statements to prevent possible SQL injection issues. As an additional note, use unambiguous date format, when you pass date values to SQL Server:
Example using PHP Driver for SQL Server:
<?php
// Connection
$serverName = env("DB_HOST");
$connectionInfo = array(
"Database"=>env("DB_DATABASE"),
"UID"=>env("DB_USERNAME"),
"PWD"=>env("DB_PASSWORD")
);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
// Statement
$employee = '000010993';
$datefrom = '20200601';
$dateto = '20200610';
$tsql = "EXEC USP_Daily_TA_Punching_Detailswith_OT ?, ?, ?";
$params = array($employee, $datefrom, $dateto);
$getResults = sqlsrv_query($conn, $tsql, $params);
if ($getResults === false) {
die(print_r(sqlsrv_errors(), true));
}
// Results
$data = array();
do {
while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
$data[] = $row;
}
} while (sqlsrv_next_result($getResults));
// End
sqlsrv_free_stmt($getResults);
sqlsrv_close($conn);
$total_row = count($data);
?>
Example using Laravel:
<?php
...
$employee = '000010993';
$datefrom = '20200601';
$dateto = '20200610';
DB::select("SET NOCOUNT ON; EXEC USP_Daily_TA_Punching_Detailswith_OT ?, ?, ?", array($employee, $datefrom, $dateto));
...
?>
Try the below to call the store procedure in laravel
DB::select("call USP_Daily_TA_Punching_Detailswith_OT('".$employee."','".$datefrom."','".$dateto."')");

php page to insert data to sql not working

I'm trying to add data to my sql server from a Unity game through a php. The php code is given below. The URL I'm testing with is
The SQL server as well as the php file is hosted in Azure, I have been able to add data through standard SQL commands etc(database connection is working properly), and running the following page when tested with the URL http://example.net/filename.php?one=4&two=8 only returns Test84, and no change is made to the table.
I would really appreciate it if someone is able to tell me as to why this is not working
<?php
//
echo"Test";
$data=$_GET[one];
$data1=$_GET[two];
echo $data1;
echo $data;
$conn = new PDO("sqlsrv:server = {}; Database = {}", "{}", "{}");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn->prepare ("INSERT INTO registratib_tbl (name,email ) VALUES ( ? , ?)");
$sql->bindParam(1, $data);
$sql->bindParam(2, $data1);
$sql->execute();
//$conn->query($sql);
echo "<h3>Data Inserted!</h3>";
?>
Please try to insert data as shown below:
<?php
$serverName = "tcp:yourserver.database.windows.net,1433";
$connectionOptions = array("Database"=>"yourdatabase",
"Uid"=>"yourusername", "PWD"=>"yourpassword");
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
//Select Query
$tsql = "SELECT [CompanyName] FROM SalesLT.Customer";
//Executes the query
$getProducts = sqlsrv_query($conn, $tsql);
//Error handling
if ($getProducts == FALSE)
die(FormatErrors(sqlsrv_errors()));
$productCount = 0;
$ctr = 0;
?>
<h1> First 10 results are : </h1>
<?php
while($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC))
{
if($ctr>9)
break;
$ctr++;
echo($row['CompanyName']);
echo("<br/>");
$productCount++;
}
sqlsrv_free_stmt($getProducts);
$tsql = "INSERT SalesLT.Product (Name, ProductNumber, StandardCost, ListPrice, SellStartDate) OUTPUT INSERTED.ProductID VALUES ('SQL New 1', 'SQL New 2', 0, 0, getdate())";
//Insert query
$insertReview = sqlsrv_query($conn, $tsql);
if($insertReview == FALSE)
die(FormatErrors( sqlsrv_errors()));
?>
<h1> Product Key inserted is :</h1>
<?php
while($row = sqlsrv_fetch_array($insertReview, SQLSRV_FETCH_ASSOC))
{
echo($row['ProductID']);
}
sqlsrv_free_stmt($insertReview);
//Delete Query
//We are deleting the same record
$tsql = "DELETE FROM [SalesLT].[Product] WHERE Name=?";
$params = array("SQL New 1");
$deleteReview = sqlsrv_prepare($conn, $tsql, $params);
if($deleteReview == FALSE)
die(FormatErrors(sqlsrv_errors()));
if(sqlsrv_execute($deleteReview) == FALSE)
die(FormatErrors(sqlsrv_errors()));
?>
For more information, please visit this article.

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