Home > front end >  At each access, get a non-random field, but from the first, second, third
At each access, get a non-random field, but from the first, second, third

Time:06-05

I have a select in mysql with php as below, I need that each access to the page takes the value of a field, whats01, whats02, whats03, whats04, but not randomly, but in sequence, and when you get to the last one, go back to the first. Anyone have an idea?

select whats01, whats02, whats03, whats04 from clients

CodePudding user response:

Here's how I would solve this:

  1. Add a Redis instance to your application in addition to the MySQL database.

  2. Before you run the SQL query, use an INCR command to get a value from a particular key in Redis. The value in that key is a 64-bit integer value that is incremented atomically, and then returned.

    INCR mykey
    
  3. Use the value returned from the Redis command in this SQL expression. It calculates the modulus of the 64-bit integer by 4 (or whatever the number of expressions you want to choose from). Add 1, then use this in MySQL's ELT() function to pick one of the arguments.

    SELECT ELT(MOD(?, 4)   1, whats01, whats02, whats03, whats04) AS whats_next
    FROM client;
    

This should create a system that makes each successive request increment the counter, and pick the corresponding column. If you have many concurrent requests, even if you have multiple instances of your application on load-balanced servers, it should still work, because the Redis counter is central. Each request will get the next incremented value.

You could do something similar with a MySQL table with a single row, but it would probably be too slow and would involve row locks that would limit your rate of traffic.

Redis is fast enough to support a high rate of requests, and will not lock any rows in MySQL.

  • Related