tags:

views:

107

answers:

2

Any reason why the following code won't work?

$dbconnection = db::getInstance();  //this is a singleton db class

$stmt = $dbconnection->prepare("SELECT `id` from `table` where `username`=?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($uid);
$stmt->fetch();

echo $uid;

The same connection method is used elsewhere, and it works there. The only difference on that other page where it works, is that there are multiple rows fetched, not just one.

edit: I get no error message. echo $uid just doesn't output anything. It's supposed to echo the user's ID from the DB (yes, that query from the DB works properly, tested it).

Can you suggest a good way to debug this if you can't immediately see a problem?

edit: Tried switching execute() and bind_result() positions, with no difference.

edit I finally got an error/warning:

*Warning: mysqli_stmt::mysqli_stmt() [mysqli-stmt.mysqli-stmt]: Couldn't fetch db*

SOLVED

Okay. I solved my problem. I guess you're not supposed to close the db connection when using a singleton class? I wasn't aware of that. The problem was, that after the "logging-in" function was being called, I did a $dbconn->close(); And later on I was grabbing the same instance, so the db connection was closed.

A: 

I try to always check the return values of each database call... most of them return at least a success/failure boolean. And you can use mysqli->error to emit something intelligible if the return value isn't what you expect. Here's an example:

  $stmt->bind_result($uid)
     or die("Error binding result - ".$stmt->error) ;

The best thing about doing that is you can leave the debugging code in, and it will be useful in narrowing the problem if there's ever a weird database connectivity problem or something.

Nathan
oh, you've got exception handling in your model... so my example using die() may not be what you want. But you can still check each return value.
Nathan
very nice suggestion thank you. however, as i edited my post above, i finally was able to output some errors/warnings. and the first one is that it cannot fetch the db. is there something wrong with my singleton class, since i can connect to the db from another page.
Sev
A: 

SOLVED

Okay. I solved my problem. I guess you're not supposed to close the db connection when using a singleton class? I wasn't aware of that. The problem was, that after the "logging-in" function was being called, I did a $dbconn->close(); And later on I was grabbing the same instance, so the db connection was closed.

Sev