0

OK, here is the situation: I have a table with the fields "ID" (int, auto incremented), "query" (text), and "counter" (int). I am trying to make it so if a selected value exists in the "query" column, the counter of that row should be increased by one. If it doesn't, then a new row should be created with the counter's value being 1. I am using this code:

$all_search_queries = $wpdb->get_results('SELECT * FROM `table`', ARRAY_A);
$found_query = false;
foreach($all_search_queries as $val){
    if($_GET['s'] == $val['query']){
        $wpdb->update('table', array('query'=>$_GET['s'], 'counter'=>$val['counter']+1), array('ID' => $val['ID']), array('%s', '%d'), array('%d'));
        $found_query = true;
        break;
    }
}
if(!$found_query){
    $wpdb->insert('table', array('query'=>$_GET['s'], 'counter'=>1), array('%s', '%d'));
}

Now what it does is it takes $val['counter']'s value and increases it by 2. If I type $val['counter']+2 then it increases it by 4. If I delete the +1 then the value remains unchanged.

Also on that last line where it inserts a new row - 'counter'=>1 actually makes the counter equal to 2. And 'counter'=>15 makes it equal to 16. What gives? This makes no sense to me. Some explanation would be really appreciated. Thanks for your time.

8
  • and you're sure this runs only once per request, and there are no duplicates in your custom table? How're you handling race conditions from when 2 people search for the same thing at the same time? What was the reasoning against using a service such as google analytics for this?
    – Tom J Nowell
    May 5, 2015 at 15:03
  • @TomJNowell This is currently done only locally and only I have access to it. I'm sure the code is executed only once. Also Google Analytics is unknown to me.
    – Nadroev
    May 5, 2015 at 15:29
  • While I can't duplicate this (don't have time) my guess is that you are having trouble because you are trying to manually manipulate an autoincrement field. Change the field type to an simple integer type and see if the weirdness disappears.
    – s_ha_dum
    May 5, 2015 at 16:04
  • Have you actually checked and verified it's only ran once? Perhaps that's your issue, you assume it runs once, it actually runs twice
    – Tom J Nowell
    May 5, 2015 at 19:05
  • @s_ha_dum Only the ID is autoincremented and I wasn't modifying it. Now I changed it to a simple int and it still happens.
    – Nadroev
    May 6, 2015 at 6:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.