How to connect php webservice to sql server 2008 r2 - php

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

Related

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

PHP Script to convert mysql data to json doesnt return anything when executed [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 6 years ago.
Im trying to fetch information from a online hosted database and convert it to json, i have the php script that i made but when i execute it, it displays a blank page where it should show the data from the database.
Here is the script:
<?php
define('HOST','---');
define('USER','---');
define('PASS','---');
// define('DB','plofenosa');
 
$con = mysqli_connect(HOST,USER,PASS);
if (!$con)
{
die ('Could not connect:' .mysqli_connect_error());
}
mysqli_select_db("plofenosa", $con);
$result = mysqli_query("SELECT * FROM Obras");
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
print json_encode($output);
mysqli_close($con);
?>
UPDATED:
<?php
define('HOST','mssql3.gear.host');
define('USER','plofenosa');
define('PASS','Xn6g_1s_IqFc');
define('DB','plofenosa');
 
$con = mysqli_connect(HOST,USER,PASS);
if (!$con)
{
die ('Could not connect:' .mysqli_connect_error());
}
mysqli_select_db("plofenosa", $con);
$result = mysqli_query("SELECT * FROM Obras");
$output = array(); //Added new line
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
print json_encode($output);
mysqli_close($con);
?>
UPDATE #2
<?php
$serverName = "---";
/* Get UID and PWD from application-specific files. */
$uid = 'plofenosa';
$pwd = '---';
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>"plofenosa");
/* 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 'Connected successfully';
$tsql = "SELECT * FROM Obras";
$stmt = sqlsrv_query($conn, $tsql);
if( $stmt === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
$json = array();
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$json[] = $row;
}
} while ( sqlsrv_next_result($stmt) );
/* Run the tabular results through json_encode() */
/* And ensure numbers don't get cast to trings */
print json_encode($json,<code> JSON_NUMERIC_CHECK</code>);
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
This syntax is incorrect
mysqli_select_db("plofenosa", $con);
it should be
mysqli_select_db($con, "plofenosa");
Note the connection variable is first not second.
If in doubt, you can always read the manual as a last resort
Or it may be simpler to use the connection to select the database
$con = mysqli_connect(HOST,USER,PASS, "plofenosa");
See the manual for mysqli_connect
and remove the mysqli_select_db() completely
Use this code
mysqli_select_db("plofenosa", $con);
$result = mysqli_query("SELECT * FROM Obras");
$output = array(); //Added new line
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
print json_encode($output);
mysqli_close($con);

how can i read from local firebird database and insert into remot MSSQL server data base by php

could any one show me how i could column from local firebird database and insert the column values into a remot Mssql database
like read column "col1" from firebird then take the data and copy it into MSSQL databas.
this will help me to get started with my project.
NOTE: I've already connect to the tho both data bases and checked the connections.
<?PHP /**********************************************/
/************THE FIREBIRDCONNECTION**************/
/**********************************************/
$host = 'localhost:c:\DATABASE.fdb';
$username='';
$password='';
$dbh = ibase_connect ( $host, $username, $password ) or die ("error in db connect"); //DB connection function
$q="SELECT COLUMN FROM TABLE WHERE CODE = ''"; // query variable
$query = ibase_prepare($q); // prepare the query to read from the DB.. send the q as a prameter
$result=ibase_execute($query); // after preaparin..run and execute the query .. send the query as a prameter
$showRow = ibase_fetch_row($result); //fitching the row
echo $showRow[0]; // row as an arry
/* free result */
ibase_free_query($query); //relase the query
ibase_free_result($result); // show the resulte
/* close db */
ibase_close($dbh); // close the connection
echo "</br>";
echo "</br>";
/**********************************************/
/************THE MSSQL CONNECTION**************/
/**********************************************/
// instance name: InstanceName
// database name: DATABASE2
$host = "SERVERNAME\InstanceName";
echo $host;
$connectionInfo = array( "Database"=>"DATABASE2", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $host, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
} ?>

Running SQL Query in PHP File

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

'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