klapsius
klapsius

Reputation: 75

sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given in

im trying print records from my db (IIS, MSSQL PHP) but i have this error...

Warning: sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given in

<?php

$serverName ="name\SQLEXPRESS";
 $usr="sa";
 $pwd="pasw";
 $db="dbname";

$connectionInfo = array("UID" => $usr, "PWD" => $pwd, "Database" => $db);

$conn = sqlsrv_connect($serverName, $connectionInfo);



  $sql = "SELECT first_col, s_col, t_col,  FROM names ";
 $res = sqlsrv_query($conn,$sql);
  while ($row = sqlsrv_fetch_array($res)) {
    print(
    $row['first_col'].",".$row['s_col'].",".$row['t_col'].");

 }  


sqlsrv_close( $conn); 
?>

Upvotes: 3

Views: 49565

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 157863

The accepted answer is too localized and of no help for most users coming from Google, who need rather a generic answer, what to do when one gets such error in general.

This error message doesn't have any particular meaning, it's just a symptom telling us that the query execution failed. While we need to get the actual error message from SQL server. Hence every query should be executed in PHP like this:

$sql = "SELECT first_col, s_col, t_col,  FROM names";
$stmt = sqlsrv_query($conn, $sql);
if($stmt === false) {
    trigger_error(print_r(sqlsrv_errors(), true), E_USER_ERROR);
}

What is going on here?

  • first, we are checking the query result, if case it's equal to false, which means the query failed
  • if so, we are calling sqlsrv_errors() which returns an array with all errors returned by SQL server
  • then we are converting this array to string using print_r()
  • and finally, throwing a conventional PHP error that could be handled the same way as any other error

In the end, a failed query will throw a PHP error that explains the reason, so one can read the SQL server error message and then fix it right away or Google this message to get the explanation/practical suggestions for their particular error

Upvotes: 1

Daniel Rocha
Daniel Rocha

Reputation: 1

If you use Stored Procedure with SQL SERVE, you must use EXEC, in your code you used CALL

$check = sqlsrv_query($conn, "{CALL Mem_Users_Accede (?,?,?,?)}", $data);

Upvotes: -1

John Conde
John Conde

Reputation: 219814

Your query failed. This causes sqlsrv_query() to return false.

Your error in your query is an errant comma:

$sql = "SELECT first_col, s_col, t_col,  FROM names ";
                                    ^^^^
                                    HERE

Remove it and your query should work.

FYI, you don't check for errors in your code. You should always check to see if something failed, and if so, get the error message. You would have caught this quickly if you did.

Upvotes: 10

Related Questions