开发者

PHP if else to check ipaddress against ones stored in table

I've got just a quick little poll and a query to check and see if the IPaddress is already in the table to kn开发者_开发百科ow if someone has already voted. I have the table created already and it works.

My question is with the if else statement it is not working. I am trying to make it

if ip address is in the table show string else show poll

$ip=$_SERVER['REMOTE_ADDR'];

include("../db/config.php");
include("../db/opendb.php");

$result = mysql_query("SELECT * FROM Poll WHERE ip='$ip'");

if ($result==$ip) {
    echo "Thank you for voting.";
} else {
    echo "<form action=logvote.php method=post>" .
         "<input type=radio name=ans value=ans1> Answer1<br>" .
         "<input type=radio name=ans value=ans2> Answer2<br>" .
         "<input type=radio name=ans value=ans3> Answer3<br>" .
         "<input type=radio name=ans value=ans4> Answer4<br>" .
         "<input type=submit value=Submit>";

    echo "<input type=hidden name=ip value=";   
    echo "$ip>";

    echo "</form>";

 include("../db/closedb.php");

}

Thanks in advance.


You simply forgot to fetch a row first. Also, you can get the necessary information with a simple count:

$result = mysql_query("SELECT COUNT(*) as 'count' FROM Poll WHERE ip='$ip'");
$row = mysql_fetch_assoc($result);

if ($row['count']) {
    // show string
} else {
    // show poll
}


Your code should be:

$query = mysql_query("SELECT ip FROM Poll WHERE ip='$ip'");
$info = mysql_fetch_object($query);
$result = $info->ip;

if($result == $ip)

mysql_query() returns a reference not a string.

Also, using ip in the SELECT statement will speed up your code.


mysql_query does not return the data directly but rather a reference to the result.

You can get the number of rows found for the query with:

$num = mysql_numrows($result);

So you can check by:

$result = mysql_query("SELECT ip FROM Poll WHERE ip='$ip'");
if (mysql_numrows($result)) {
    // dostuff
} else {
    // do other stuff
}

// you can retrieve the ip like so:
$data = mysql_fetch_assoc($result);
$ip = $data['ip'];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜