1

can you maybe help me please? I'm making my voting system in php + mongodb, and I would like to keep the ip addresses which already voted. What would be to best way? I was thinking about doing it like this:

$ip=$_SERVER['REMOTE_ADDR'];
$ipData = array('$push' => array('ips' => $ip), '$inc' => array('votes' => 1));
$collection->update(array( '_id' => $id), $ipData);

Is this the best way to do it? How would you than compare all the elements of the ips array to see if the ip already didn't voted? The list will look like (192.168.0.1, 127.0.0.1, 123.45.67.8).

Thank you!

mrkva
  • 336
  • 2
  • 13

2 Answers2

2

Use a Unique Index and a UPSERT:

$collection->ensureIndex(array('ips'), array('unique' => true));
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
-3

compare the user's ip with the array of IPs using the PHP function in_array()

http://php.net/manual/en/function.in-array.php

Oliver M Grech
  • 3,071
  • 1
  • 21
  • 36
  • First of all, there was no need to vote down, because if you read his question carefully, that is what he asked "How would you than compare all the elements of the ips array to see if the ip already didn't voted?" I would do store them in a database, create a unique index or search before inserting a new vote + ip. I answered him according to what he asked! – Oliver M Grech May 02 '11 at 14:49
  • Sorry, but there is. I read the question carefully, but maybe you didn't? It is also tagged `mongodb`... If he has half a million IPs you would retrieve them all and, if PHP doesn't run out of memory, check for duplicates using `in_array` which should be pretty slow. Even if he doesn't use unique indexes, the least you could suggest is issuing a query limited to one result on the database for that specific IP, `in_array()` is just crazy here. – Alix Axel May 02 '11 at 14:57