CodeIgniter Forums

Full Version: How to add a counter to a MySQL Table?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Mohsen32[/eluser]
I have a table named "ads" and want to add counter to my ads view to show how many times an ad in table "ads" has been visited by users.
Hope I maid it clear.
Thanks.

El Forum

[eluser]davidbehler[/eluser]
- Add a column named "ads_click_count" or something like that to your table
- The link on the Ad should be to one of your sites, e.g. ads/view/ad_id
- On that site you simply update the ads table for ad_id and increase the counter field by one, e.g.
Code:
$query = "Update ads set ads_click_count = ads_click_count + 1 where ads_id = ".$this->db->escape($ads_id).";";
// You could use active records aswell
- After updating the counter you redirect to the real destination of the ad, e.g.
Code:
redirect('http://www.google.de');

That should be it. There are more ways to do this, e.g. use Javascript, but that's what I came up with in a hurry

El Forum

[eluser]Mohsen32[/eluser]
Is this gonna work:

Code:
$data = array(
'click_count' => 'click_count + 1'
);

$this->db->select('click_count')->where('id', $row->id);
$this->db->update('ads', $data);

El Forum

[eluser]thePiet[/eluser]
[quote author="Mohsen32" date="1249046548"]Is this gonna work:

Code:
$data = array(
'click_count' => 'click_count + 1'
);

$this->db->select('click_count')->where('id', $row->id);
$this->db->update('ads', $data);
[/quote]

More something like:

Code:
$data = array(
'click_count' => 'click_count + 1'
);

$this->db->where('id', $some_id);
$this->db->update('ads', $data);

I guess.

El Forum

[eluser]davidbehler[/eluser]
You will propably have to disable escaping:
Code:
$this->db->set('click_count', 'click_count + 1', FALSE);
$this->db->where('id', $some_id);
$this->db->update('ads');

El Forum

[eluser]Mohsen32[/eluser]
Thanks, Worked.

El Forum

[eluser]Unknown[/eluser]
i had the same problem, and i still wanted to pass an array to the update function,

using:
Code:
$this->db->set($data, false);

didn't worked.

so i solved it with this code:

Code:
function update($id, $data)
{
   $data = array(
      'click_count' => 'click_count + 1'
   );

   foreach($data as $k => $v)
   {
      $this->db->set($k, $v, false);
   }
   $this->db->where('id', $some_id);
   $this->db->update('ads');
}

hope that helped.