Problems with getting Tables from Databases using sqlsrv_query in php - php

I am having problems with sqlsrv_query in PHP. I get the following warning:
Warning: sqlsrv_query() expects parameter 1 to be resource, null given in C:\xampp\htdocs\Status.php on line 76
Notice: Array to string conversion in C:\xampp\htdocs\Status.php on line 76
A error occured: Array
This is my code:
<?php
$conn = OpenConnectionMsSQL();
#var_dump($conn);
$sql_select = "Select state_desc from sys.databases";
$params = array();
$query = sqlsrv_query($conn, $sql_select, $params) or die('A error occured:' . sqlsrv_errors());
$res = sqlsrv_num_rows($query);
while($row = sqlsrv_fetch_assoc($res))
{ echo ($row['state_desc']); }
?>
and this is my connection code:
<?php
function OpenConnectionMsSQL()
{
try{
$serverName = "***";
$database = "***";
$uid = "***";
$pwd = "***";
$connectionOptions = array("Database"=>"$database","Uid"=>"$uid","PWD"=>"$pwd");
$conn = sqlsrv_connect($serverName, $connectionOptions);
if($conn == false)
die( print_r( sqlsrv_errors(), true));
}
catch(Exception $e)
{
exit("<h1>"."Verbindung fehlgeschlagen!". "</br>". "Server Stopped"."</h1>");#.$e->getMessage());
exit("<!--"."<h1>"."Serverstatus: Verbindung fehlgeschlagen!". "</br>". "Server Stopped"."</h1>"."-->");#.$e->getMessage();
}
}
?>
How do I fetch my results correctly?

I just forgot to use sql_fetch_array, so I couldn't fetch my results.
The following snippet fixes the problem
$sql_select = "Select state_desc,name from sys.databases where name='master'";
$sql_version = "Select ##version as Version";
$stmt = sqlsrv_query($conn, $sql_select) or die('A error occured: ' . print_r( sqlsrv_errors(), true));
$version = sqlsrv_query($conn, $sql_version) or die('A error occured: ' . print_r( sqlsrv_errors(), true));
if (sqlsrv_has_rows($version)) {
$data2 = sqlsrv_fetch_array( $version, SQLSRV_FETCH_ASSOC);
echo "Serverinfo: ".$data2['Version']."<br/>"."<br/>";
} else {
echo "No data found";
}

Related

I'm trying to display rows in SQL Server with php

the response i get after making connection and running the query is "resource(4) of type (SQL Server Connection)"
<?php
$serverName = "xx.xx.xx.xx";
$uid = "sa";
$pwd = "xxxxxxxxxx";
$databaseName = "courierdb";
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>$databaseName);
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
var_dump($conn);
/* Execute the query. */
$sql = "SELECT * FROM dbo.AwbDomestics";
$stmt = sqlsrv_query( $conn, $sql);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
if (sqlsrv_has_rows($stmt)) {
echo "row:<br>"; var_dump($row); echo "<br><br>";
}
else {
echo "<br/>No Results were found.";
}
}
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
how do i select all the rows in the database without this "resource(4) of type (SQL Server Connection). Any help is much appreciated.
The if (sqlsrv_has_rows($stmt)) test should be around the loop, not inside it.
if (sqlsrv_has_rows($stmt)) {
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
echo "row:<br>"; var_dump($row); echo "<br><br>";
}
else {
echo "<br/>No Results were found.";
}
}
To check for errors from the query, you should check if $stmt is FALSE, not $conn. So change
if ($conn == false)
to
if (!$stmt)
You may try with this script. Using sqlsrv_has_rows() is not necessary. Use sqlsrv_fetch_array() or sqlsrv_fetch()/sqlsrv_get_field() to retrieve data.
<?php
/* Warnings */
sqlsrv_configure("WarningsReturnAsErrors", 1);
/* Connection */
$serverName = "xx.xx.xx.xx";
$uid = "sa";
$pwd = "xxxxxxxxxx";
$databaseName = "courierdb";
$connectionInfo = array(
"UID" => $uid,
"PWD" => $pwd,
"Database" => $databaseName
);
$conn = sqlsrv_connect(
$serverName,
$connectionInfo
);
if ($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
/* Execute the query with sqlsrv_fetch_array(). */
$sql = "SELECT * FROM dbo.AwbDomestics";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
//print_r($row, true);
foreach($row as $field => $value) {
echo $field.": ".$value." ";
}
echo "\n";
}
/* Execute the query with sqlsrv_fetch()/sqlsrv_get_field(). */
$sql = "SELECT * FROM dbo.AwbDomestics";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
$fc = sqlsrv_num_fields($stmt);
while (sqlsrv_fetch($stmt)) {
for($i = 0; $i < $fc; $i++) {
echo sqlsrv_get_field($stmt, $i, SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_CHAR))." ";
}
echo "\n";
}
/* End */
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>

Php - Call to undefined function mssql_query()

I have used the following php code to show the number of rows from sql table but I am getting below error message.
Fatal error: Call to undefined function mssql_query()
in D:\wamp\www\thereport24\gp.php
on line 22
my code:
$conn = odbc_connect('gpcon','','');
if ($conn)
{
$query= "select * from SubscriberServices where SubscriptionGroupID like 'ms_gp_tr24bn_3333'";
$results = mssql_query($query);
$rows = mssql_fetch_array($results);
echo $rows[0];
mssql_close($con);
}
If you use sql server, use this code. This works for me:
<?php
$serverName = "serverName";
$options = array( "UID" => "sa", "PWD" => "Password", "Database" => "DBname");
$conn = sqlsrv_connect($serverName, $options);
if( $conn ) {
echo "Connection established.<br />";
$query="select * from SubscriberServices where SubscriptionGroupID like 'ms_gp_tr24bn_3333'";
$result = sqlsrv_query($conn,$query);
sqlsrv_close($conn);
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>
if it returns "Connection established." it's mean you install MS SQL Drivers correct.

How to read from Firebird database and insert the data into MSSQL database?

I want to select some columns from Firebird database and insert them in MSSQL database tables.
When I read the table from Firebird it represent exactly what I need in the localhost, then when I want to insert the data into MSSQL it only inserts the last record. I don't know what cause this, and it's my first time to try this idea.
Would someone tell me what goes wrong?
This is my PHP code:
<?php
$host = 'localhost:c:\firebird.fdb';
$username='';
$password='';
$dbh = ibase_connect($host, $username, $password);
$stmt = "SELECT * FROM TWEEKDAY";
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
$R1 = $row->CODE;
$R2 = $row->DAYNAME;
echo $R1 ." ". $R2 . "\n";
echo "</br>";
}
ibase_close($dbh);
/**********************************************/
$host = "servername\instancename";
$connectionInfo = array( "Database"=>"MSSQLdatabase", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $host, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
echo "</br>";
$tsql = "INSERT INTO [AccessCard].[dbo].[WEEKDAY] (DAYID,DAYN) VALUES ('$R1','$R2')";
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
while( $obj = sqlsrv_fetch_object( $stmt , SQLSRV_FETCH_ASSOC) ) {
echo $obj->DAYID ."&nbsp ". $obj->DAYN . "<br />";
}
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
When i run my code, it shows in local host as :PIC1
and when i open the mssql database that what the table have:PIC2
it seems like it insert the last value of $R1 $R2.
and when i use this code:
<?php
$host = 'localhost:c:\FIREBIRD.fdb';
$username='';
$password='';
$dbh = ibase_connect($host, $username, $password);
$stmt = "SELECT * FROM TWEEKDAY";
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
$R1 = $row->CODE;
$R2 = $row->DAYNAME;
echo $R1." ". $R2 . "\n";
echo "</br>";
}
ibase_close($dbh);
/**********************************************/
$host = "SERVERNAME\INSTANCENAME";
$connectionInfo = array( "Database"=>"AccessCard", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $host, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
echo "</br>";
for ($RIdx = 0; $RIdx < count($R1); $RIdx++) { // each $R array value
$tsql = "INSERT INTO [AccessCard].[dbo].[WEEKDAY] (DAYID,DAYN) VALUES ('$R1[$RIdx]','$R2[$RIdx]')";
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
} // end of insert loop
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
This is what show in the database:PIC3
$R1 should be an array, as in $R1[] = $row->CODE; Also $R2' obviously. Change your sqlserver insert accordingly. I don't have sql server installed here so i cannot provide tested code.
Here is the sql server code...
$host = "servername\instancename";
$connectionInfo = array( "Database"=>"MSSQLdatabase", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $host, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
echo "</br>";
for ($RIdx = 0; $RIdx < count($R1); $RIdx++) { // each $R array value
$tsql = "INSERT INTO [AccessCard].[dbo].[WEEKDAY] (DAYID,DAYN) VALUES ('$R1[$RIdx]','$R2[$RIdx]')";
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
} // end of insert loop
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
Finaly the problem solved:
here is the solution code
<?php
$host = 'localhost:c:\firebird.fdb';
$username='';
$password='';
$dbh = ibase_connect($host, $username, $password);
$stmt = "SELECT * FROM TWEEKDAY";
/**********************************************/
$host = "servername\instancename";
$connectionInfo = array( "Database"=>"AccessCard", "UID"=>"", "PWD"=>"");
$conn = sqlsrv_connect( $host, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
echo "</br>";
/**********************************************/
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
$R1 = $row->CODE;
$R2 = $row->DAYNAME;
echo $R1." ". $R2 . "\n";
$tsql = "INSERT INTO [AccessCard].[dbo].[WEEKDAY] (DAYID,DAYN) VALUES ('$R1','$R2')";
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
while( $obj = sqlsrv_fetch_OBJECT( $stmt) ) {
echo $obj->$R1."&nbsp ". $obj->$R2. "<br />";
$obj++;
}
echo "</br>";
}
ibase_close($dbh);
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
thank you Ryan for your help, it seems that the solution came to my mind while i'm editing my question.
thanks again.

Fetching a result from selection query in php function

I have a php function of selection from mySql database:
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
$db=mysql_select_db($NAME_DB);
$qry = "SELECT tax_id FROM master where name =".$name." and latin =".$latin;
echo $qry;
$result = mysql_query($qry);
while ($Res_user = mysql_fetch_assoc($result) ) {
return $Res_user['tax_id'];
}
}
an error is shown Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/admin/public_html/hitlist/include/fg_membersite.php on line 446 and the line is while ($Res_user = mysql_fetch_assoc($result)
So what is the problem ? How can i fix it?
Try this
function Master_file($name, $latin ){
$dsn = 'mysql:host=localhost;dbname=nom';
$username = 'utilisaeur';
$password = 'K3Pud1';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
$result = $db->prepare("SELECT tax_id FROM master where name =:name");
$result->bindValue(':name', $name);
$result->execute();
foreach($result->fetchAll(PDO::FETCH_ASSOC) as $row){
echo $Res_user['tax_id'] . '<br />';
}
}
EDIT
The function above has just been updated to use PDO, display any errors, and output the tax_id value to the browser
You may try this, since your returning here return $Res_user['tax_id']; so I think you need a single row instead
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
if (!$connect) {
die("Could not connect: " . mysql_error());
}
$db=mysql_select_db($NAME_DB, $connect);
if (!$db) {
die ("Can't use " . $NAME_DB . " : " . mysql_error());
}
$qry = "SELECT tax_id FROM master where name ='" . $name . "' and latin = '" . $latin . "'";
$result = mysql_query($qry);
if( $result ){
$row = mysql_fetch_assoc($result);
return $row['tax_id'];
}
}

Not getting anything back from sqlsrv_num_rows

I'm trying pull back data from MS SQL via a php page. I have got a valid connection, and am trying a simple SELECT * FROM MyTable but sqlsrv_num_rows is just blank no matter what I do!!!
Here is my code:
function connect() {
$serverName = DB_HOST; //serverName\instanceName
$connectionInfo = array( "Database"=>DB_NAME, "UID"=>DB_USER, "PWD"=>DB_PASSWORD);
$this->connection = sqlsrv_connect( $serverName, $connectionInfo);
sqlsrv_connect( $serverName, $connectionInfo);
if( $this->connection ) {
echo "<br>Connection established.<br />";
}else{
echo "<br>Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
}
The echo for Connection established is working so all AOK there!
Now when I do a simple query:
function query($sql) {
if ($this->debug) {
echo $sql . "<br />";
}
$this->sql = $sql;
$this->recordset = sqlsrv_query($this->connection, $sql);
if (!$this->recordset) {
die('<br><br>Invalid query :<br><br><bold>' . $this->sql . '</bold><br><br>' . sqlsrv_errors());
}
echo "<br>rows = " . sqlsrv_num_rows($this->recordset);
I get absolutely nothing from the above echo? Any reason why? Or can you suggest a new echo I can try to debug this?
All my code in my DB class is converted from mysql so there may be a few bits wrong that is doing the damage!
I've even tried a super simple version, all the code together and it's still blank/false:
$server = DB_HOST;
$conn = sqlsrv_connect( $server, array( "Database"=>DB_NAME, "UID"=>DB_USER, "PWD"=>DB_PASSWORD) );
$stmt = sqlsrv_query( $conn, "SELECT * FROM MyTable");
$row_count = sqlsrv_num_rows($stmt);
echo "<br>row count = " . $row_count;
if ($row_count === false)
echo "\nerror\n";
else if ($row_count >=0)
echo "\n$row_count\n";
die;
Try this.....
Replace below statement
sqlsrv_query( $conn, "SELECT * FROM MyTable");
as
sqlsrv_query( $conn, "SELECT * FROM MyTable", array(), array("Scrollable"=>"buffered"));

Categories