Luke Litherland Luke Litherland - 7 days ago 6
MySQL Question

PHP - Why is my Query returning NULL?

i was wondering why my query is returning null when i know there is data there.

my query is as follows:

if (isset($_POST['noteid']))
{
$showNoteInfo = "SELECT Note FROM Notes WHERE NoteID = 2";
$showNotes = sqlsrv_query($conn, $showNoteInfo);

var_dump($showNotes);
}


I have tested $_POST['noteid'] and that displays an ID no problem, in theory this id will replace where i have the number 2 in my query.

However i know in my table in the Notes table where NoteID = 2 the text should be like this enter image description here

however var_dump displays "resource(7) of type (SQL Server Statement)"

and i have also tried a different method of displaying it and that returned as the query expected resource and was given NULL, so why is this query not getting any results?

my connection details are in an include at the top of the page and are like this: http://pastebin.com/qz3tScdW

If you need anything else please ask.

Underlying question, why is my Query returning NULL when i know theres data there?

Answer

You never actually try to retrieve your data. sqlsrv_query performs the database query, but it doesn't get the data. You need to use sqlsrv_fetch_array (or sqlsrv_fetch_object) for that:

$stmt = sqlsrv_query($conn, $showNoteInfo);

if (sqlsrv_has_rows($stmt)) {
    $data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
    var_dump($data['Note']);
} else {
    echo "No data found";
}