PHP sqlsrv query to database

user3185936 picture user3185936 · Apr 17, 2014 · Viewed 49k times · Source

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

Answer

Quijote Shin picture Quijote Shin · Jul 2, 2014

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