0

Can I select and update together? Instead of use 2 queries, can I use just one?

SELECT data FROM log limit 1

update log SET `data` = $now where `id` = 1

any ideas?

RGS
  • 4,062
  • 4
  • 31
  • 67
  • What are you trying to accomplish? What would be the result of such operation? – Kamil Gosciminski Sep 18 '16 at 21:38
  • @KamilG. I want to allow just one user to read this date, the first one who opens the page and this first user should update the date. a function will be avaliable each 5 minutes, can't be avaliable for 2 users at the same time. This way, select and update together in a MyISAM engine I can do what I want, can't i? – RGS Sep 18 '16 at 21:45
  • 1
    You can't do `SELECT` and `UPDATE` in one query. Use a transaction to prevent someone else from changing the database between the queries. – Barmar Sep 18 '16 at 22:01
  • 1
    Transactions don't work in MyISAM, so use `LOCK TABLE data`. – Barmar Sep 18 '16 at 22:02

1 Answers1

1

Lock the table to prevent another user from updating the table.

LOCK TABLES data;
SELECT data FROM log WHERE id = 1;
// fetch the result
UPDATE log SET data = NOW() WHERE id = 1;
UNLOCK TABLES;
Barmar
  • 741,623
  • 53
  • 500
  • 612