in reply to
How do I handle a DB error when a SQL statement must not fail?
I suspect that the root cause of the problem is right here:
$sql = "SELECT SLEEP(10);";
This is asking the SQL service engine to sleep. This is probably stoppering things up. Furthermore, it’s holding a transaction open for ten seconds, and this I wager is the root cause of your deadlocks.
If you need to take a snooze, your application program should do this on its own. It should not keep a transaction open during the duration.