views:

55

answers:

4

I am fairly new to coding in php and have come accross a bit of a problem which I think is very simple. I am trying to capture the IP address of anybody that visits my website and stores that in my database. The code is as follows, I am not even sure the code will work but I do get the following error Parse error: syntax error, unexpected T_INC on line 29 which I will highlight in the code:

$ip = $_SERVER['HTTP_CLIENT_IP']; 
                $query="SELECT * FROM ip";
                $result = mysql_query($query);
                $num = mysql_numrows($result);
                $i = 1;
                $found=false;
                while(($i - 1) < $num){
                    $selection = mysql_query("SELECT ip FROM ip WHERE id=$i");
                    $tip = mysql_fetch_assoc($selection);
                    if($tip == $ip){
                        $found = true;
                    }
                i++; //This is line 29
                }
                if($found == false){
                    $sql = "INSERT INTO `rowley_blog`.`ip` (`ip`) VALUES ('$ip');";
                    mysql_query($sql);
                    mysql_close();
                }
+6  A: 

You need to prefix variables with $, so it's $i++.

chelmertz
I knew it was going to be something really simple and stupid thank you!
SamRowley
@SamRowley: if you use an IDE or code editor which highlights your code, typos like these could easily be avoided. I recommend netbeans.org (their PHP version).
chelmertz
+2  A: 

It should be this:

$i++;
Mark Byers
+1  A: 

You need to put a dollar sign before all your variables - that should be

$i++;
Sam Dufel
+1  A: 

Apart from the syntax error: This code seems blown-up to me. Doesn't this do the same:

$ip = $_SERVER['HTTP_CLIENT_IP'];
mysql_query("REPLACE INTO `ip` (`ip`) VALUES ('" . mysql_real_escape_string($ip) . "')");

Remember: Good code is short code ;)

Furthermore: If you are only beginning to code PHP, please don't even start using the mysql_ extension. Instead use PDO:

$ip = $_SERVER['HTTP_CLIENT_IP'];
$db->query("REPLACE INTO `ip` (`ip`) VALUES ('" .$db->quote($ip) . "')");
nikic