Executing stored procedure in php laravel - php

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."')");

Related

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

Exec SQL Server stored procedure from PHP

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

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

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.

Azure Mobile Service, making HTTP calls via PHP

I have created a demo app, "todo" app. I am using mobile service of windows azure. Hence I have a database called "todo" and tables inside it. Now I can access this database from android java code(as seen in tutorials). But now I have a website that need to access this database created by android app. Can PHP access this mobile service database anyhow?
Thanks in advance.
The database created as part of the Windows Azure Mobile Services creation is 'just' a Windows Azure SQL database instance meaning you could use the SQL Server Driver for PHP to connect to it.
See how to article here, an extract -
<?php
$serverName = "tcp:ProvideServerName.database.windows.net,1433";
$userName = 'ProvideUserName#ProvideServerName';
$userPassword = 'ProvidePassword';
$dbName = "TestDB";
$table = "tablePHP";
$connectionInfo = array("Database"=>$dbName, "UID"=>$userName, "PWD"=>$userPassword, "MultipleActiveResultSets"=>true);
sqlsrv_configure('WarningsReturnAsErrors', 0);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if($conn === false)
{
FatalError("Failed to connect...");
}
CreateTable($conn, $table, "Col1 int primary key, Col2 varchar(20)");
$tsql = "INSERT INTO [$table] (Col1, Col2) VALUES (1, 'string1'), (2, 'string2')";
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt === false)
{
FatalError("Failed to insert data into test table: ".$tsql);
}
sqlsrv_free_stmt($stmt);
$tsql = "SELECT Col1, Col2 FROM [$table]";
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt === false)
{
FatalError("Failed to query test table: ".$tsql);
}
else
{
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC))
{
echo "Col1: ".$row[0]."\n";
echo "Col2: ".$row[1]."\n";
}
sqlsrv_free_stmt($stmt);
}
sqlsrv_close($conn);
function CreateTable($conn, $tableName, $dataType)
{
$sql = "CREATE TABLE [$tableName] ($dataType)";
DropTable($conn,$tableName);
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
FatalError("Failed to create test table: ".$sql);
}
sqlsrv_free_stmt($stmt);
}
function DropTable($conn, $tableName)
{
$stmt = sqlsrv_query($conn, "DROP TABLE [$tableName]");
if ($stmt === false)
{
}
else
{
sqlsrv_free_stmt($stmt);
}
}
function FatalError($errorMsg)
{
Handle_Errors();
die($errorMsg."\n");
}
function Handle_Errors()
{
$errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
$count = count($errors);
if($count == 0)
{
$errors = sqlsrv_errors(SQLSRV_ERR_ALL);
$count = count($errors);
}
if($count > 0)
{
for($i = 0; $i < $count; $i++)
{
echo $errors[$i]['message']."\n";
}
}
}
?>
The Azure web site has a dedicated PHP section. Check out the link below to find some examples.
http://www.windowsazure.com/en-us/develop/php/

Categories