I'm trying to display rows in SQL Server with php - 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);
?>

Related

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

how to get the while loop three different variable into the json array

actually i try to write the program from get the ms sql data select and then selected data insert to the MySQL table.i write the program which one get the final value of the table. because insert query place out side the while loop.how do i get the all the value in to the insert query??
I think can store in the while loop execution data json array.can i retrieve the one by one?
MSSQL DB connection
<?php
$serverName = "servername"; //serverName\instanceName,
portNumber (default is 1433)
$connectionInfo = array( "Database"=>"Databasename",
"UID"=>"username", "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));
}
?>
test.php
<?php
require_once ('inc/MSSQL_connection.php');
//require_once ('inc/MYSQL_connection.php');
$query ="SELECT EnrolledID,Date,Time FROM dbo.view_attendance
ORDER BY Date,Time";
$result = sqlsrv_query($conn,$query);
if ($result == FALSE){
die(FormatErrors(sqlsrv_errors()));
}
else{
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$emp_no = $row['EnrolledID'];
$date = date_format($row['Date'], 'Y-m-d');
$time = date_format($row['Time'], 'H:i:s');
}
//echo $emp_no;
$conn = mysqli_connect("localhost", "root", "","kelaniya");
$query = "INSERT INTO attendancedata (EnrolledID,Date,Time) VALUES ('{$emp_no}', '{$date}', '{$time}')";
mysqli_query($conn, $query);
}
?>
IMHO you can just move insert into while loop, why not?:
<?php
require_once ('inc/MSSQL_connection.php');
//require_once ('inc/MYSQL_connection.php');
$query ="SELECT EnrolledID,Date,Time FROM dbo.view_attendance
ORDER BY Date,Time";
$result = sqlsrv_query($conn,$query);
if ($result == FALSE){
die(FormatErrors(sqlsrv_errors()));
}
else{
$conn_insert = mysqli_connect("localhost", "root", "","kelaniya");
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
$emp_no = $row['EnrolledID'];
$date = date_format($row['Date'], 'Y-m-d');
$time = date_format($row['Time'], 'H:i:s');
//echo $emp_no;
// MySQLli
$stmt = $conn_insert->prepare('INSERT INTO attendancedata (EnrolledID,Date,Time) VALUES (?,?,?)');
// I insert as string as was in original question (table metadata was not given...)
$stmt->bind_param('sss', $emp_no, $date, $time ); // 's' specifies the variable type => 'string'
$stmt->execute();
}
}
?>

Populate drop down form SQL server using PHP and HTML

Whenever I try to run the below code, I get the passed variable ". $record . " as it is.
I am trying to populate a drop-down from a database, but I keep getting a value which I am passing in the while loop.. I know I am making a simple mistake.Can someone please help to solve this issue
<select name="c" multiple="multiple">
<option>--select--</option>
<?php
$dbname = "abc";
$serverName = "xyz"; //serverName\instanceName
try
{
$connectionInfo = array( "Database"=>$dbname);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$SQL_string= "Select distinct [CC] from [abc].[dbo].
[abcdefg] ";
$stmt = sqlsrv_query($conn, $SQL_string);
$records[] = array();
while ($row = sqlsrv_fetch_array($stmt,
SQLSRV_FETCH_ASSOC))
{
$records[] = $row['CC'];
}
foreach ($records as $record)
{
echo' <option value="'. $record . '">' .$record.
'</option>';
}
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
catch(Exception $ex)
{
echo "Connection failed: " . $ex->getMessage();
}
?>
Here's an attempt at simplifying this a bit. I can't guarantee it will work, but it may bring to light the error you are facing:
<select name="c" multiple="multiple">
<option>--select--</option>
<?php
$dbname = "abc";
$serverName = "xyz"; //serverName\instanceName
try
{
$connectionInfo = array( "Database"=>$dbname);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$SQL_string= "Select distinct [CC] from [abc].[dbo].[abcdefg];";
$stmt = sqlsrv_query($conn, $SQL_string);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
echo '<option value="'.$row['CC'].'">'.$row['CC'].'</option>';
}
sqlsrv_free_stmt( $stmt);
}
catch(Exception $ex)
{
echo "Caught exception error: " . $ex->getMessage();
}
?>
</select>

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.

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