Converting my code from mysql to SQL server (SQLsrv), but having issue founding the equlent to mysql_field_name as used here:
foreach($this->aCols as $i=>$col)
{
if($col['c']=='')
{
if(is_string($col['f']))
$this->aCols[$i]['c']=ucfirst($col['f']);
else
$this->aCols[$i]['c']=ucfirst(mysql_field_name($res,$col['f']));
}
}
I think it would be sqlsrv_get_field(). See below MSDN document (link) for documentation and code samples:
sqlsrv_get_field
Syntax:
sqlsrv_get_field( resource $stmt, int $fieldIndex)
Taken from MSDN (A sample usage):
$tsql = "SELECT ReviewerName, Comments
FROM Production.ProductReview
WHERE ProductReviewID=1";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false )
{
echo "Error in statement preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Make the first row of the result set available for reading. */
if( sqlsrv_fetch( $stmt ) === false )
{
echo "Error in retrieving row.\n";
die( print_r( sqlsrv_errors(), true));
}
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";
Related
SQL Stored Procedure returns NULL when I call it from my mobile app or a web browser, but the same procedure returns what it has to when called using SQLPro for MSSQL software
if( $conn == FALSE ) {
echo "Connection failed.";
die( print_r( sqlsrv_errors(), true));
}
$query = "EXEC dbo.sp_Pok_Details #oe=17,#code='5907769000409'";
$getProducts = sqlsrv_query($conn, $query);
if ($getProducts == FALSE)
{
die(FormatErrors(sqlsrv_errors()));
}
while($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC))
{
$returnArray[] = $row;
}
echo json_encode($returnArray);
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.
If you can't change your stored procedure, use sqlsrv_next_result() to make the next result active and then fetch the data.
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 (based on your code):
<?php
if( $conn === false ) {
echo "Connection failed.";
die( print_r( sqlsrv_errors(), true));
}
$query = "EXEC dbo.sp_Pok_Details #oe = ?, #code = ?";
$params = array(17, '5907769000409');
$getProducts = sqlsrv_query($conn, $query, $params);
if ($getProducts === false) {
die( print_r( sqlsrv_errors(), true));
}
// Just for test - make additional call(s) to get the count of the active result sets
do {
while($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC)) {
echo 'Current rowset'.'<br>';
}
} while (sqlsrv_next_result($getProducts));
// Or if you have only one result set
//while ($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC)) {
// $returnArray[] = $row;
//}
echo json_encode($returnArray);
?>
Although this question has already been answered multiple times here, here, and here, none of these solutions could solve the issue for me.
I am trying to use PHP to fetch data from an MSSQL database. Although any query that I attempt to perform yields the same error message:
The active result for the query contains no fields.
Below is the code that I use to execute the query.
<?
include 'private.php'; // contains the servername, database, userID and password
$connectionInfo = array( "Database"=>$database, "UID"=>$userID, "PWD"=>$password);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
$query = 'USE data; SELECT * FROM Users;';
$stmt = sqlsrv_query( $conn, $query );
if(sqlsrv_has_rows($stmt))
{
echo 'success';
}
$row = sqlsrv_fetch_array( $stmt);
if ($row === false)
{
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['Name'].", ".$row['Value']."<br />";
}
sqlsrv_free_stmt( $stmt);
}
else {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
Surprisingly, executing the same query in Microsoft SQL Server Management Studio works without any errors and executing queries that do not return information work fine aswell.
Note that I have already tried using SET NOCOUNT ON;, which is recommended in some answers regarding the same topic.
How can I resolve this error?
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
The last parameter '$status' is suppose to return a 0 or 1. How do I get the value of that output parameter? Echoing $result always returns 1. The stored procedure works under classic asp and .NET, but I need to do it under PHP.
$conn = sqlsrv_connect($serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$tsql = "{call spName(?,?,?,?)}";
$params = array(
array(&$param1, SQLSRV_PARAM_IN),
array(&$param2, SQLSRV_PARAM_IN),
array(&$param3, SQLSRV_PARAM_IN),
array(&$status, SQLSRV_PARAM_OUT)
);
$stmt = sqlsrv_prepare($conn, $tsql, $params);
if($stmt===false ) {
if( ($errors = sqlsrv_errors() ) != null) {
die( print_r( sqlsrv_errors(), true));
}
$result = sqlsrv_execute($stmt);
if($result === false){
die( print_r( sqlsrv_errors(), true));
}
echo " " . $result;
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
Unbelievable, all I had to do was echo the output parameter itself ($status in this example) to see the result.
I am working on a php code where I insert into two tables and want to grab the id from the first table I inserted into, right now I am getting this error: Call to undefined function sqlsrv_field(). I am trying to grab the routine_id from the table routines.
Code:
date_default_timezone_set('Europe/Oslo');
$date = strftime ('%Y-%m-%d');
$time = strftime('%H:%M:%S');
$value = $_GET['Temp'];
$conn = sqlsrv_connect('BILAL' , $conn_array);
$sql = "Insert into routines (date, time, value, emp_id) values ('$date', '$time', '$value', (SELECT id FROM emps WHERE user_name='Arduino'))";
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$query = sqlsrv_query( $conn, $sql);
if( $query === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_next_result($query);
sqlsrv_fetch($query);
$id = sqlsrv_field($query,0);
$sql2 = "Insert into measure_routines (routine_id, measure_id, pool_id) values ('$id', (Select id from measurements where title='A_Auto_Temperatur'), 1 )";
$stmt = sqlsrv_query( $conn, $sql2);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
There is no function called sqlsrv_field(). Instead, use sqlsrv_get_field():
...
sqlsrv_next_result($query);
bool fetchStatus = sqlsrv_fetch($query);
if(fetchStatus === false) {
die( print_r( sqlsrv_errors(), true));
}
if(fetchStatus === null) {
// Some work when there are no results in the result set
} else {
$id = sqlsrv_get_field($query, 0);
}
...
This should solve your problem basically. However your code is vulnerable to SQL injection. Instead of giving values directly into the sql query, consider using prepared statements.
There are many articles about that, here is one I found in quick search:
What's the Right Way to Prevent SQL Injection in PHP Scripts?
Try this:
function lastId($queryID) {
sqlsrv_next_result($queryID);
sqlsrv_fetch($queryID);
return sqlsrv_get_field($queryID, 0);
}
$lastInsertedId = lastId($stmt);