mysql问题,检查项目是否存在

时间:2011-03-18 21:20:05

标签: php mysql

$gt = 'andrew';

mysql_connect('localhost', '', '');
mysql_select_db('database');
$result = mysql_query("SELECT gamertag FROM register WHERE gamertag = '".$gt."'");

while ($row = mysql_fetch_assoc($result)) {
    $gt = $row['gamertag'];
}

if($gt = 'andrew') {
    echo 'This gamertag has previously been registered!';
}

5 个答案:

答案 0 :(得分:7)

巨大的问题:

if($gt = 'andrew'){
echo 'This gamertag has previously been registered!';
}

将始终评估为true ....将$gt = 'andrew'替换为$gt == 'andrew'

答案 1 :(得分:1)

$gt = 'andrew';

mysql_connect('localhost', '', '');
mysql_select_db('database');
$result = mysql_query("SELECT gamertag FROM register WHERE gamertag = '".$gt."'");

if(mysql_num_rows($result) > 0){
    echo 'This gamertag has previously been registered!';
}

答案 2 :(得分:1)

if($gt = 'andrew'){
echo 'This gamertag has previously been registered!';
}

您需要==来测试相等性。将上述内容更改为:

if($gt == 'andrew'){
echo 'This gamertag has previously been registered!';
}

您可能还有SQL注入漏洞。您应该至少使用mysql_real_escape_string()

上的$gt

答案 3 :(得分:0)

while ($row = mysql_fetch_assoc($result)) {
    $gt = $row['gamertag'];
}

if($gt = 'andrew'){
echo 'This gamertag has previously been registered!';
}

此代码似乎没必要。看起来你可以轻松做到:

while($row = mysql_fetch_assoc($result)){
     echo 'This gamertag has previously been registered!';
}

只要有结果,就知道标签已被使用。如果没有结果,则while循环中的代码将不会执行,即名称尚未使用。

答案 4 :(得分:0)

您的查询已在检查该项目是否存在。从这里我们可以看出,如果查询返回任何行,则该项存在。所以你的代码可以简单:

if(mysql_num_rows($result)) {
    echo 'This gamertag exists!'
}