Running SQL Query in PHP File - php

I have established a connection with my SQL Database through Windows Authentication in my php file. However I'm not sure how the syntax will look if I wanted to display a simple SQL query such as (Select * from Media) on the php page that shows an entire table. I tried a few methods but it displayed a fatal error.
Here is my code for the php:
<?php
$serverName = "172.20.90.170,5050"; //serverName\instanceName
// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"TestDB");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$version = mssql_query('SELECT * FROM MEDIA');
$row = mssql_fetch_array($version);
echo $row[0];
?>
Fatal Error:
Fatal error: Call to undefined function mssql_query()
This establishes a succesful connection but what would I need to change in my code for this query to run error free and display the required output?

It appears you are mixing two different API's (sqlsrv_ and mssql_).
If you're using sqlsrv_, then a simple statement could look like:
$connectionInfo = array( "Database" => "database", "UID" => "username", "PWD" => "password" );
$conn = sqlsrv_connect( "Server", $connectionInfo );
$stmt = "SELECT [column] FROM [table] WHERE [id] = ?";
$params = array( $id );
$query = sqlsrv_query( $conn, $stmt, $params );
if( $query === false ) {
print( print_r( sqlsrv_errors() ) );
}
while( $row = sqlsrv_fetch_array( $query, SQLSRV_FETCH_ASSOC )) {
echo $row['column'];
}
sqlsrv_close( $conn );
Resources
MSDN Documentation
PHP Documentation (contains both Windows & SQL Server authentication examples)

From what I understand, you're new to the PHP world, BUT, I advise you to use the PDO class. You will have more facility to do what you want.
Here's a sample using your data.
If you study, you can understand.
try
{
$connection = new PDO("sqlsrv:Server=172.20.90.170;Database=TestDB", "YOUR_USERNAME", "YOUR_PASSWORD");
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection->setAttribute(PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ENCODING_SYSTEM);
}catch (Exception $e)
{
echo $e->getMessage();
die('Connection could not be established.<br />');
}
try
{
$sql = 'SELECT * FROM MEDIA';
$query = $connection->prepare($sql);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}catch (Exception $e)
{
die('Cant fetch rows.');
}
foreach ($result as $r)
{
print_r($r); // do what you want here
}

As others says in the comments, you have two options:
1. Use sqlsrv_query
2. Install MSSQL support to PHP.
Sincerely, I prefer use mssql_* stack of functions. If you use ubuntu, you can install MSSQL support simply:
aptitude install php5-sybase

Related

"The active result for the query contains no fields" using MSSQL with PHP

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?

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

How to connect php webservice to sql server 2008 r2

We are developing php webservice and our database is on sql server 2008 r2
/* sql connection string */
$link = mssql_connect('localhost','usrname','pass') or die('Cannot connect to the DB');
mssql_select_db('Data Source=PC-NAME;Initial Catalog=DBNAME.MDF;Persist Security Info=True',$link) or die('Cannot select the DB');
/* grab the posts from the db */
echo $query = "SELECT * FROM add_product WHERE prod_pos = '".$_GET['prod_pos']."'";
$result = mssql_query($query,$link) or die('Errant query: '.$query);
it gives fatal error on mssql_connect.
Fatal error: Call to undefined function mssql_connect() in service.php on line 11
So how to connect php webservice with sql server 2008 r2???
Thanks in advance...
You will need to download and install the sqlsrv extension from Microsoft. Look here for one option: http://www.microsoft.com/en-us/download/details.aspx?id=20098
Note that the extension is no longer called "mssql" but is instead now "sqlsrv" so you'll want to use sqlsrv_connect(), etc.
Got the Answer..............
<?php
$number_of_posts = $_GET['prod_pos'];
$format = 'json';
/* connect to the db */
$serverName = "(local)";
/* Get UID and PWD from application-specific files. */
$uid = "usrname of sql server 2008";
$pwd = "password";
$connectionInfo = array( "UID"=>$uid, "PWD"=>$pwd, "Database"=>"db name" );
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
echo "Unable to connect.</br>";
die( print_r( sqlsrv_errors(), true));
}
/* Query SQL Server for the login of the user accessing the database. */
$tsql = "SELECT * FROM add_product WHERE prod_pos='".$number_of_posts."'";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false )
{
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
/* create one master array of the records */
$posts = array();
while($post = sqlsrv_fetch_array($stmt) )
{
$posts[] = array('post'=>$post);
}
/* output in necessary format */
if($format == 'json')
{
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
}
/* disconnect from the db */
$stmt = null;
$conn = null;
?>
Successfully connected to the sql server 2008 r2 database using php

'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