Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you need to close mysqli statements?

Tags:

php

mysqli

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.
like image 290
Bono Avatar asked Oct 31 '22 12:10

Bono


1 Answers

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.)

like image 147
Jacob Budin Avatar answered Nov 15 '22 06:11

Jacob Budin