How can the problem of multiple processes executing the same MySQL query and processing duplicate data be resolved in PHP?

Issue: To prevent multiple processes from executing the same MySQL query and processing duplicate data in PHP, we can use locking mechanisms like mutex or semaphores to ensure only one process can access and execute the query at a time.

// Acquire a lock before executing the MySQL query
$lock = sem_get(1234); // Create a semaphore with key 1234
sem_acquire($lock);

// Execute the MySQL query
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

// Process the query result
while ($row = mysqli_fetch_assoc($result)) {
    // Process each row
}

// Release the lock after processing the query
sem_release($lock);