2014-06-13 36 views
0

我創建了一個web服務,我調用了一個函數來確認用戶,但是每次我調用該函數時,即使我發送了錯誤的代碼,我也會收到「註冊確認」消息,這裏是我的函數的實現,考慮ckey是恆定不變的,vercode是每個用戶可變的,我認爲這個問題是關於mysql指令的。我選擇的PHP函數無法正常工作

// RPC method 2 (confirm user) 
function confuser($ckey, $vercode) { 
    $db = mysql_connect("localhost","root"); 
    if(!$db){ 
     return 'Error: cannot open the connection'; 
     exit; 
    } 

    mysql_select_db('user_info'); 
     $query = "select * from personal where vercode='".$vercode."' and ckey='".$ckey."' "; 
     $result = mysql_query($query, $db); 
     if($result){ 
      return 'registration confirmed'; 
      } 
      else{ 
       return 'wrong verification , send it again!'; 
      } 
} 
+0

使用'mysql_num_rows',看看是否有行或不http://www.php.net//manual/en/function .mysql-num-rows.php –

回答

0

mysql_query()將對任何成功的查詢返回結果句柄。這包括返回ZERO行的查詢。零行結果仍然是一個有效的結果,它恰好沒有任何內容。您不會在零行查詢中獲得「錯誤」返回。

您需要檢查找到的行數,例如

$result = mysql_query(...); 
if (!$result) { 
    die(mysql_error()); // in case something did blow up 
} 
if (mysql_num_rows($result) == 0) { 
    ... wrong verification ... 
} 
0
mysql_select_db('user_info') or die(mysql_error()); 
$query = "select * from personal where vercode='$vercode' and ckey='$ckey'"; 
$result = mysql_query($query, $db) or die(mysql_error()); 
if(mysql_num_rows($result) > 0) 
    return 'registration confirmed';  
return 'wrong verification , send it again!'; 

請注意,你需要確保你的變量$ vercode和$ CKEY。 mysql_real_escape_string()被用作escape方法,但是現在使用了mysql_real_escape_string(),並且您使用的大多數函數將從PHP 5.5.0開始被棄用。或者您可以使用PDO prepared statements

2

您可以使用這樣的事情:

if(mysql_num_rows($result) > 0){ 
    return 'registration confirmed'; 
} 
else{ 
    return 'wrong verification , send it again!'; 
} 
+0

你會想要使用@vivek sharma的答案。如果成功執行,$ result將始終返回true。計算返回的行數是檢查給定信息是否存在的最佳方法。 – user1890328