Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP sqlsrv query to database

I am migrated from MySQL to MS SQL Server, and trying to fetch all data from the routines table. I am connected but unsure how to fetch data with sqlsrv. This is how far I have came:

$conn_array = array (
    "UID" => "sa",
    "PWD" => "root",
    "Database" => "nih_bw",
);
$conn = sqlsrv_connect('BILAL', $conn_array);
if ($conn){
    echo "connected";
    $result = sqlsrv_query($db->db_conn,"SELECT * FROM routines");
}else{
    die(print_r(sqlsrv_errors(), true));
}
sqlsrv_close($conn);
?>
like image 445
user3185936 Avatar asked Apr 17 '14 11:04

user3185936


People also ask

What does Sqlsrv_query return?

Returns a statement resource on success and false if an error occurred.

What is Sqlsrv_query?

sqlsrv_query — Prepares and executes a query. sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction. sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed. sqlsrv_send_stream_data — Sends data from parameter streams to the ...

What is Sqlsrv_fetch_array?

The sqlsrv_fetch_array function always returns data according to the Default PHP Data Types. For information about how to specify the PHP data type, see How to: Specify PHP Data Types. If a field with no name is retrieved, the associative key for the array element will be an empty string ("").

Does PHP work with SQL Server?

The Microsoft Drivers for PHP for SQL Server enable integration with SQL Server for PHP applications. The drivers are PHP extensions that allow the reading and writing of SQL Server data from within PHP scripts.


2 Answers

First if I'm not wrong you are storing sqlsrv_connect result into $conn and this result isn't a class obj its a resource, so remove $db->conn

This example, will connect, then fetch if there are resources returned from sqlsrv_query

$conn_array = array (
    "UID" => "sa",
    "PWD" => "root",
    "Database" => "nih_bw",
);
$conn = sqlsrv_connect('BILAL', $conn_array);
if ($conn){
    echo "connected";
    if(($result = sqlsrv_query($conn,"SELECT * FROM routines")) !== false){
        while( $obj = sqlsrv_fetch_object( $result )) {
              echo $obj->colName.'<br />';
        }
    }
}else{
    die(print_r(sqlsrv_errors(), true));
}
like image 72
Quijote Shin Avatar answered Sep 22 '22 15:09

Quijote Shin


After you've successfully executed the query with sqlsrv_query you can fetch the results, e.g., by using sqlsrv_fetch_array:

$result = sqlsrv_query($db->db_conn, "SELECT * FROM routines");
if($result === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC) ) {
    echo $row['column1'].", ".$row['column2']."<br />";
}
like image 44
Mureinik Avatar answered Sep 19 '22 15:09

Mureinik