Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "close" database when the query happens?

Tags:

php

mysql

$database->count = "SELECT * FROM table WHERE item_id = 1"

if($database->count == 1)
{
   $database->update = "UPDATE users SET money = money - 1000";
   $database->delete = "DELETE table WHERE item_id = 1";
}

Let's say I have this code (I've just created it) in index.php page. Can at the same time "SELECT * FROM table WHERE item_id = 1" query happen so two people would get count 1 and -1000 money? If yes, how can I avoid that?

Thank you.

like image 464
good_evening Avatar asked Apr 12 '11 15:04

good_evening


People also ask

Should I close DB connection after query?

For the purpose of safe coding, you should always close database connections explicitly to make sure that the code was able to close itself gracefully and to prevent any other objects from reusing the same connection after you are done with it.

How do you close a database?

Once you are done using the database, you must close it. You use the DB->close() method to do this. Closing a database causes it to become unusable until it is opened again. It is recommended that you close any open cursors before closing your database.


1 Answers

If you're worried about two queries running at the same time being responsible for unbalanced state in your DB, you should be using transactions : http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-transactions.html

Transactions are helpful in keeping the state of your data correct.

like image 59
JohnP Avatar answered Sep 21 '22 12:09

JohnP