Not getting anything back from sqlsrv_num_rows - php

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

Related

MS SQL statements work in DBeaver but not in PHP (with configuration and setup correct)

I have the following code to verify that my PHP-MS SQL connection and configuration are setup properly. I have about 100 getter functions that are all set up the same to retrieve info from this database:
function ms_getClientLN($repEnvKey) {
$repCustKey = '';
$serverName = "1.1.1.1\\EDGESQL"; //serverName\instanceName
$connectionInfo = array( "Database"=>"EDGESQL", "UID"=>"userid", "PWD"=>"password");
$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));
}
$sql = "SELECT repCustKey FROM repair WHERE repEnvKey LIKE '$repEnvKey';";
//echo $sql . "<br>";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
} else {
#echo "0 results";
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$repCustKey = $row['repCustKey'];
}
sqlsrv_close( $conn );
//----------===== Get ClientLast from customer table =====----------
$serverName = "1.1.1.1\\EDGESQL"; //serverName\instanceName
$connectionInfo = array( "Database"=>"EDGESQL", "UID"=>"userid", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$clast = '';
if( $conn ) {
//echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT cuLastName FROM customers WHERE cuKey LIKE '$repCustKey';";
//echo $sql . "<br>";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
} else {
#echo "0 results";
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$clast = $row['cuLastName'];
}
sqlsrv_close( $conn );
return $clast;
}
I then have the following function formatted exactly like the other working hundred that produces no results:
function ms_getRepairHistory($rhRepKey) {
$type = '';
$results[] = array();
$serverName = "1.1.1.1\\EDGESQL"; //serverName\instanceName
$connectionInfo = array( "Database"=>"EDGESQL", "UID"=>"userid", "PWD"=>"password");
$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));
}
$sql = "SELECT rhWhen, rhWhereNext, rhNotes FROM RepairHistory WHERE rhRepKey LIKE '$rhRepKey';";
echo $sql . "<br>";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
} else {
echo "0 results<br>";
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results[] = $row;
}
sqlsrv_close( $conn );
return $row;
}
I'm even echoing the SQL command and can copy and paste it into DBeaver:
echo $sql . "<br>";
outputs:
SELECT rhWhen, rhWhereNext, rhNotes
FROM RepairHistory
WHERE rhRepKey LIKE '001-167896-001';
Which works in DBeaver with the
Databse.dbo.
prefix attached:

Show all database in sqlsrv by php

I want to display all databases in microsoft sql srv for admin panel, but i have problem with get value. I'm try with query:
EXEC sp_databases
This query is executed successfully in sql srv, but when i'm try make this same by PHP, im not see value, no any errors or warnings, return null
My PHP Code:
<?php
$serverName = $_POST['hostname'];
$uid = $_POST['username'];
$pwd = $_POST['password'];
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd);
$connsrv = sqlsrv_connect( $serverName, $connectionInfo);
if($connsrv == TRUE ){
echo "connected";
$tsql = "EXEC sp_databases";
$stmt = sqlsrv_query( $connsrv, $tsql);
while( $row = sqlsrv_fetch_array($stmt)){
echo $row['DATABASE_NAME'];
}
}else{
echo "no connect";
}
?>
I don't know why I not see any result - any suggestions ? :(
One possible explanation for this unexpected behaviour is that CREATE DATABASE or ALTER ANY DATABASE or VIEW ANY DEFINITION permissions are requied to run the sp_databases stored procedure (I can reproduce this with a server login, which has only public role). Set the needed permissions for the connection user, or as another option, try to use the sys.databases system view.
<?php
// Connectuion
$serverName = $_POST['hostname'];
$uid = $_POST['username'];
$pwd = $_POST['password'];
$connectionInfo = array("UID" => $uid, "PWD" => $pwd);
$connsrv = sqlsrv_connect($serverName, $connectionInfo);
if ($connsrv === false){
echo "Not connected";
exit;
}
// sp_databases
echo "Connected. EXEC sp_databases: "."<br>";
$tsql = "EXEC sp_databases";
$stmt = sqlsrv_query( $connsrv, $tsql);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while( $row = sqlsrv_fetch_array($stmt)){
echo $row['DATABASE_NAME']."<br>";
}
sqlsrv_free_stmt($stmt);
// sys.databases
echo "Connected. SELECT * FROM sys.databases: "."<br>";
$tsql = "SELECT * FROM sys.databases";
$stmt = sqlsrv_query( $connsrv, $tsql);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
while( $row = sqlsrv_fetch_array($stmt)){
echo $row['name']."<br>";
}
sqlsrv_free_stmt($stmt);
// End
sqlsrv_close($connsrv);
?>

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

SQL query into option form

I have a PHP code to get info from my Microsoft SQL server 2014, but it isnt working, the page it self works fine since it pops up as it should when i comment out the PHP code, but as soon as the PHP code isnt commented out, its just all white, so im assuming problem with the PHP code. I have to get the results from the query out into a drop down menu.
i use this code:
$servername = "VCCSQL03";
$username = "forecast";
$password = "Telefon2";
$dbname = "Forecast";
$connectionInfo = array("Database"=>$dbname, "UID"=>$username, "PWD"=>$password);
$conn = sqlsrv_connect($serverName, $connectionInfo);
if(!$conn) {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
// Check connection
$result = sqlsrv_query($conn,"SELECT * FROM dbo.vw_BrandProduct");
if ($result->num_rows > 0) {
// output data of each row
while($row = sqlsrv_fetch_array($result)) {
echo "<option value='".$row['Brand_ProductID']."' name='".$row['Brand_ProductName']."'</option>";
}
} else {
echo "";
}
sqlsrv_close();
First and foremost, you do not have an open and closed select tag, and your option tags was missing a > to close it properly. Try the below revision, assuming connection is established on the page properly then this should work.
$connectionInfo = array( "Database"=>$dbname, "UID"=>$username, "PWD"=>$password);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if(!$conn) {
//// Check connection
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$result = sqlsrv_query($conn,"SELECT * FROM dbo.vw_BrandProduct");
if ($result->num_rows > 0) {
// output data of each row
echo "<select name='products'>";
while($row = sqlsrv_fetch_array($result)) {
echo "<option value='".$row['Brand_ProductID']."'>$row['Brand_ProductName']</option>";
}
echo "</select>";
} else {
echo ""; } sqlsrv_close(); ?>

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.

Categories