I created a microsoft sql stored procedure, and I am calling it from the php code below. I do not get any errors, but I do not get any output either. I have looked all over, but I am still fuzzy about how to do the WHILE statement to retrieve the variables I need from sql... I am hoping someone can take a look at the php code below (and the sql code below that) to see what I might be missing. Oh, and when I execute the stored procedure through SQL, it works fine and returns the data I expect. Thanks!
<?php
$serverName = "PRATHIBA-PC\SQL2008";
$connectionInfo = array( "Database"=>"TMS", "UID"=>"sa", "PWD"=>"asset12345" );
//$connectionInfo = array( "Database"=>"TMS");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Define the Transact-SQL query. Use question marks (?) in
place of the parameters to be passed to the stored procedure
*/
$tsql_callSP = "{call Getstudentname( 1 )}";
$studentid = '1';
$params = array(
array($studentid, SQLSRV_PARAM_IN)
);
/* Execute the query. */
$stmt3 = sqlsrv_query( $conn, $tsql_callSP, $params);
if( $stmt3 === false ) {
echo "Error in executing statement 3.\n";
die( print_r( sqlsrv_errors(), true)); }
/* Display the value of the output parameters. */
while (sqlsrv_fetch_object($stmt3)) {
// SET PARAMETERS - SET TERMS
//echo $term;
}
/*Free the statement and connection resources. */
while ($obj=sqlsrv_fetch_object($stmt3)) {
// SET PARAMETERS - SET TERMS
echo $obj->term;}
sqlsrv_free_stmt( $stmt3);
?>
This is SQL Server stored procedure code
USE [TMS]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[Getstudentname]
SELECT 'Return Value' = #return_value
GO
When I run this code I am getting output:
exec Getstudentname 1;
this is my output in sql server
1 Vivek Johari vivek#abc.com
Please help me guys..
You could try using a question mark as a place-holder for the parameter like this:
$tsql_callSP = "{call Getstudentname(?)}";
Not sure if this will help?
Related
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;
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 the following object which I am parsing from Javascript to PHP via an AJAX post request.
What is the best way to safely insert this data into SQL using PHP?
All of the keys of the object exist as columns in a table. So I thought that I'd need to find a way to loop through the object and create a statement like:
insert into table (email, first_name, last_name) VALUES ('email#host.net', 'Joe', 'Bloggs'),('email2#host2.net', 'Fred', 'Flintstone')
However, I have a suspicion that this method would open me up to the risk of SQL injection.
I have heard of 'Prepared Statements' as a way to accomplish the this with mysqli however, I am not sure if this works in sqlsrv.
This is what I have so far:
<?php
$serverName = "server";
$connInfo = array("Database"=>"database", "UID"=>"sa", "PWD"=>"password");
$conn = sqlsrv_connect($serverName, $connInfo);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$json = file_get_contents("php://input");
$data = json_decode($json, true); /// <----- THIS IS THE OBJECT WHICH HAS BEEN PARSED FROM JS VIA AJAX
$sql = ""; /// <--- I need to create an insert statement???
/////Execute the statement
if($conn){
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}//end if
echo json_encode("Record created successfully. ");
}//end if
/////End of Execute the statement
}//end if
else{
echo json_encode("ERROR: record did not save correctly to MSSQL.");
die( print_r(sqlsrv_errors(), true));
}//end else
?>
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);
?>
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