Bono
Bono

Reputation: 4869

Do you need to close mysqli statements?

Problem


I'm trying to count if there is a registration with the same telephone number and date. This is to prevent people from registering two reservations on the same date(time). My problem is that I'm expecting the query to return 0, because there is no registration with the same details in the database. The result however is 1. Which would indicate that there is already something in the database with the same info, but there isn't. My guess is that it has to do with the query I'm executing before the current query. I'm wondering if I should try closing the statement.

What have I tried


I have tried closing the statement $stmt->close() but to no avail. I tried to create new variables in stead of reusing the ones from the previous query, but that didn't work either. I triple checked the database to make sure there is no registration with the same details in there, and I'm 100% sure there is nothing wrong in the database.

Code


Here is my code. I think the problem lays in the first query part.

$query = "SELECT count(*) as reservation_amount FROM reservation WHERE `date`= ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $datetime);
$stmt->execute();
$stmt->bind_result($count);
while($row = $stmt->fetch()){
    $res_count = $row; //res_count is 1 in this case. I'm thinking I need to close something here?
}

$query = "SELECT count(*) as registered FROM reservation WHERE `number` = ? and `date`= ?";
$stmt = $db->prepare($query);
$stmt->bind_param("is", $number, $datetime);
$stmt->execute();
$stmt->bind_result($count);
while($row = $stmt->fetch()){
    $registered = $row; //outputs 1 but I'm expecting 0
}

Input


datetime = 2014-12-28 17:00:00
number = 0612345678

Database


The database contains the following record:

id  name    surname number  email           date                amount
5   Henk    Houtman 9060666 [email protected] 2014-12-28 17:00:00 1

Errors


No errors.

Upvotes: 5

Views: 372

Answers (1)

Jacob Budin
Jacob Budin

Reputation: 10003

mysqli_stmt_fetch will return true on success. If successful, your query will always return one and only one row (because you're requesting a COUNT, with the one row containing the value you're seeking).

while($row = $stmt->fetch()){
    $registered = $count;
}

You should be using the bound variable $count in determining the value in the row returned. (Note: You do not need the $row variable.)

Upvotes: 2

Related Questions