Quote:
|
Originally Posted by Nodda4me
Hello forum! I'm wondering how to detect duplicate entry and remove it before adding it to a database. I also would like to know how to sort a list by IP and by name.
Thanks,
Nodda4me
PHP Code:
$song=$_GET['song']; $ver=$_GET['ver']; $date=date("Y-m-d G:i:s"); $date2=date("D M j"); $time=date("g:i:s A"); $ip=$_SERVER['REMOTE_ADDR']; mysql_connect($host,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query = "INSERT INTO `LF` VALUES ('','$date','$time','$ip','$song', '$date2', '$ver')"; mysql_query($query);
mysql_close();
|
This is one of the ways you may use to weed out the dupes.
PHP Code:
$result = mysql_query("SELECT * FROM ..... WHERE Field1=someValue and Field2 = someValue");
$count = mysql_num_rows($result);
if ( $count == 0 )
{
$query = "INSERT INTO `LF` VALUES ('','$date','$time','$ip','$song', '$date2', '$ver')";
mysql_query($query);
}
else
{
echo "Dupes aint allowed";
}
sorting is done by appendind this to the end of the select statement:
ORDER BY Field1,Field2... [asc/desc]
The only issue may be the IP sorting since the way computers sort numbers is not the way we always want them to be sorted. For instance, given these three values 1,5,12 the sort result may be the following:
1
12
5
In order to remedy the problem you will need to left pad the elements to be sorted with a 0 as illustrated below:
01
05
12
Of course it would be silly to show IP in the format 069.123.001.003 so the left padding needs to be done in the background. There are a few wways to do that; you may try one of the two below:
1. create a variable (or an array of variables) in which each IP address would have an equivalent with the left padded zeros. This will however require you to use one of the commonly used sorting algos such as QuickSort, BubbleSort etc. Not difficult but some find it easier to do as much as possible in SQL rather than the programming language code. SQL uses B-Trees and/or other advanced data structures too, so things are much faster.
2. The second method (one I would recommned) will involve the following:
- add a field to the table, say IP_SORT
- every time a record is added, prefix IP fields entered by user with Zeros and add thus prefixed value to the IP_SORT field as a new value. For instance, if someone posts 24.150.67.6 change it to
024.150.
067.
006. Notice that IP field already containing 3 digits gets no 0 prefix. Other fields get:
Number of Prefix Zeros = 3 - Number of Digits on the IP Field
3. When you need to display the records sorted by IP do the following query:
PHP Code:
Select IP_ADDRESS, SONGNAME, DATE from SomeTable where something=blah_blah
Order by IP_SORT [,someSecondarySortField]
Hope this helps.