S
S
svm2020-09-13 20:53:47
PHP
svm, 2020-09-13 20:53:47

How to prohibit the simultaneous execution of a certain piece of code with several simultaneous connections?

I don't know how to properly ask Google, but I'm sure the answers are already there.
In general, the essence is the following. There is a php script (a certain section), this script works with the database. This script adds data to tables if the data does not exist. By itself communications at tables, including plural are adjusted.
The fact is that sometimes duplicates of this data are added while connecting and adding the same data. The first connection apparently checks that the data does not exist and decides to add it at the time when the second one began to check this data, and also makes the appropriate decision.
I thought that transactions would help me, but it wasn’t there. After I set them up, it only got worse.
All data is added. The first connection is still checking and adding all the data, the second connection is doing the same, since the first connection has not yet made its commit and the results of all work are not reflected.

What is the right thing to do in my case? I'm trying to get something from Google, but really did not find anything, except for SyncMutex.
To be honest, I don’t even know if it is and how it works in general.
In my understanding, it would somehow be possible to block the work of a certain section of code until the same section of code is executed in another connection, but I don’t know how to do this.
Table type innodb, if that.
Connection to the database is carried out through PDO.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanatPHP, 2020-09-13
@FanatPHP

This is a common mistake made by newbies who confuse transactions with locks.
You need the latter
like this and formulate it - how to lock the table for reading
and not some abstract "piece of code"

V
Vitsliputsli, 2020-09-13
@Vitsliputsli

In my opinion, the simplest and most correct solution here is insert ignore, another option for a transaction with a table lock, but this can hit performance hard.

P
profesor08, 2020-09-14
@profesor08

Classic. Do a SQL check.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question