php - mysql query inserting data multiple times

I have a table log_Data where i log searched keyword that user enter. I am facing an issue that mysql query is inserting data multiple time. query is super simple INSERT INTO TABLE_NAME (id, keyword, date_adde) ... but if user enter some word... the query will insert it and after some seconds it will insert again and sometimes it insert same record for 4 5 times.

How can i limit and make this insertion more accurate so i can avoid duplication and get better and more accurate search reports.

EDIT

inside my controller i have:

        if(isset($this->request->get['search']) && $this->request->get['search'] != ' '){
            $search_log = array(
                'keyword' => $this->request->get['search'],
                'source'  => '0', //0 for website and 1 for application
                'total_result' => $product_total
            );
            $this->model_catalog_product->searchLog($search_log);
        }

Inside my Model i have:

public function searchLog($data){
    $query = $this->db->query("INSERT INTO search_log SET keyword = '" . $this->db->escape($data['keyword']) . "', record = '" . (int)$data['total_result'] . "', customer_id = '" . (int)$this->customer->getId() . "', source = '" . (int)$data['source'] . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', date_added = NOW()");
}

attached an image where a customer searched for heel 'highlighted with black' is inserted 7 times with difference in few seconds... the customer originally searched for 1 time only... same as for other words as well...

enter image description here

Answer

Solution:

first, check your code. Secound make a unquiq key:

md5 ( keyword + date + hour )

Answer

Solution:

  • try to avoid duplicate in any form by adding session protection add hidden input call it doupleprotection it is value come from randomization like rand(1000, 10000000000) or md5(time()) then save this value in session like $_SESSION['doubleprotection']
  • Afer submit form and before inserting in database compare input value with $_SESSION['doubleprotection'] , if equal do query then give $_SESSION['doubleprotection'] new value from rand(1000, 10000000000)
  • if input value and $_SESSION['doubleprotection'] not equal stop query

Source