I have a php script which enables user to write something and after clicking some button the written data will be inserted to the mysql table data
along with the current timestamp
. Simple enough. Now since I want to pull the data from the table based on the highest timestamp
, I expect my query to pull only a single row of data that will be the last row. Keeping this in mind I cannot allow 2 or more users to insert the data at the same time which will generate exactly the same timestamp which in return will go against my purpose while querying the data. Though I know that the odds of generating exactly the same timestamp is very low, but I want to be on the safe side. Here's what I have tried out
$sql_lock_table = $db->prepare("LOCK TABLES comments WRITE");
$sql_lock_table->$db->execute();
$time = time();
$data = "some data";
$sql_insert = $db->prepare("INSERT INTO data VALUES(null, :time, :thedata)");
$sql_insert->execute(array(
"time" => $time,
"thedata" => $data
));
$sql_unlock_table = $db->prepare("UNLOCK TABLES");
$sql_unlock_table->$db->execute();
I have got the lock and unlock thing from another stackoverflow question but I have not understood clearly why locking the table before inserting, since it wont allow anybody to insert data. And so I figured out that I was right. No insertion is happening. What should I do to achieve what I wanted to do?