Get ID of Last Entery in MSSQL Server via PHP - php

Hello i need a little Help.
I have a MSSQL Server and i need the ID of the Last Entery.
My PHP Code is:
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$sqlnextid = "Select IDENT_CURRENT('dbo.Person')";
echo $sqlnextid;
$nextid = sqlsrv_query( $conn, $sqlnextid );
echo $nextid;
Unfortunately $nextid only returns "Resource id#3" and not the correct ID in the SQL Management Studio. The sql query "Select IDENT_CURRENT('dbo.Person')" works fine an give the correct answer - (33).
Where is my mistake? Thanks in advance :)

You need to fetch the data from the executed query uisng sqlsrv_fetch_array(). As is explained in the documentation, the function sqlsrv_query() returns a statement resource or false if the statement cannot be created and/or executed.
As a side note, always check the result from the sqlsrv_connect() and sqlsrv_query() calls.
<?php
...
// Connection
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
// Query
$sqlnextid = "SELECT IDENT_CURRENT('dbo.Person') AS [CurrentIdent]";
$stmt = sqlsrv_query( $conn, $sqlnextid );
if( $stmt === false ) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
// Data
$ident = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$ident = $row["CurrentIdent"];
}
echo $ident;
...
?>

sqlsrv_query returns returns a statement resource on success and FALSE if an error occurred.
You can access the result using sqlsrv_fetch_object.
$sqlnextid = "SELECT IDENT_CURRENT('dbo.Person') AS LastId"
$result = sqlsrv_query($conn, $sqlnextid);
$row = sqlsrv_fetch_object($result)
echo $row->LastId;

Related

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

Cannot bring output rows of sql server into php using sqlsrv

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?

PHP Script cant see the result of a query in json format, no errors displayed

I am trying to get the values of a table from a MSSQL Database hosted online, however, I cant get any data from it, I already looked several times in the code and cant find a error or some mis-type in the code.
I get both echos confirming connection and query were executed but then after that i should be able to see the json, but nothing is displayed, I am sure the query is correct because I use it in other places.
NOTES:
I have the sqlsrv PHP extension
The script:
<?php
error_reporting(1);
$serverName = "...";
/* Get UID and PWD from application-specific files. */
$uid = '...';
$pwd = '...';
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>"programaplo"
);
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
echo "Unable to connect.</br>";
die( print_r( sqlsrv_errors(), true));
}
echo "Conexão: sucesso \n";
$tsql = "SELECT * FROM Obras";
$stmt = sqlsrv_query($conn, $tsql);
if( $stmt === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
echo "Query: sucesso \n";
$json = array();
while($row = SQLSRV_FETCH_ASSOC($stmt)) {
$json[] = $row;
}
/* Run the tabular results through json_encode() */
/* And ensure numbers don't get cast to trings */
echo json_encode($json);
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>

Basic data retrieval using $row

I am using PHP 5.6 and SQL Server 2012 with a nonthreadsafe driver. I have an incredibly easy question I already know, but for some reason i am completely brain dead.
I have a basic SQL query that will can either return 1 row of data, or multiple.
There is only three fields with data. but I would like to be able to read off the data (this is going into a vXML ivr using Voice Server 4.0, but that is irrelevant to my question).
Here is my code:
<?php
$serverName = "localhost";
$connectionOptions = array("Database"=>"mydb");
/* Connect using Windows Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionOptions);
if( $conn ) {
echo "Connection established.";
}else{
echo "Connection could not be established.";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT * FROM my_table WHERE SSN = 111111111";
//////I have no idea if I need this or not input appreciated
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
?>
All I would like to do is be able to retreive the information as rows, like
echo $row['field'];
echo $row['field2'];
echo $row['field3'];
ect.
would someone be able to point me in the right direction? I can only find mysqli examples, and those do not seem to work. Thanks!
I assume what you're looking for is sqlsrv_fetch_array
sqlsrv_fetch_array — Returns a row as an array
An Example:
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['field'].", ".$row['field2']."<br />";
}
PHP Manual: sqlsrv_fetch_array

'Not a valid ss_sqlsrv_stmt resource' error when trying us a php function to return sqlsrv_query result

I have recently switched a PHP app from mssql to sqlsrv and would like to continue using a couple custom functions to handle all my SQL requests. I get an error
Warning: sqlsrv_fetch_array(): 2 is not a valid ss_sqlsrv_stmt
resource in...
when using the following function to handle all sqlsrv_query() calls:
<?php
function tko_query($sql)
{
//Check for db connection
$serverName = "server\sqlexpress";
$connectionInfo = array( "Database"=>"db", "UID"=>"uid", "PWD"=>"pwd");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
return sqlsrv_query($conn,$sql, array(), array('Scrollable' => 'buffered'));
}
$sql = "SELECT * FROM jobs";
$stmt = tko_query($sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
echo $row['name']."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
You should declare $conn variable as global or try to fetch data inside tko_query function body. When tko_query ends the connection is closed and you cannot fetch data..

Categories