Reputation: 42863
$res = $db->query("SELECT COUNT(*) as cnt FROM table")->fetchAll(PDO::FETCH_ASSOC);
if ( $res[0]['cnt'] == 0 ) {
$db->query("
INSERT INTO table (col)
VALUES
('value1'),
('value2'),
('value3'),
....
");
}
Suppose 2 users requested this code same time,
So, for first user, count will return 0
and INSERT query will executed, but there is possible that while first insert executed, for second user, count return also 0
? (and in this case second insert query will also executed, what I don't need).
If this is possible, how to prevent this? Using Transactions
will help in such cases ?
Upvotes: 0
Views: 199
Reputation: 23759
So, you want to insert only if there are no records in the table. Transactions won't help you.
You can use a WRITE LOCK:
Only the session that holds the lock can access the table. No other session can access it until the lock is released.
https://dev.mysql.com/doc/refman/5.0/en/lock-tables.html
Use the following method:
mysql> LOCK TABLES t1 WRITE;
mysql> SELECT COUNT(*) FROM t1;
mysql> INSERT INTO t1 (col)
VALUES
('value1'),
('value2'),
('value3');
mysql> UNLOCK TABLES;
If another session tries to execute the command LOCK TABLES t1 WRITE;
, it will wait until the first session finishes. So COUNT will always return the correct value.
Upvotes: 2