2017-04-24 27 views
-2

好吧,我很困惑。我有一些代碼在數據庫表中搜索用戶名,然後使用if else語句運行一些代碼,具體取決於是否找到用戶。我的代碼如下。問題是代碼甚至沒有看到if語句,我不知道爲什麼。任何幫助表示讚賞。PHP如果Else聲明不適用於數據庫

$sqluser = "select * from users where username='" . $user ."'"; //Searching to see if the user is in the database 
echo $sqluser . "<br><br>"; //writes out the select statement to make sure it is correct 
$query = mssql_query($sqluser); //returns the results 
$num_rows = mssql_num_rows($query); //gets the number of rows returned 

echo $num_rows; //writes out the number of rows 

if ($num_rows==0) //determines what happens next if the user exists or not 
{ 
    //displays an error box if the user doesn't exist 
    echo "<script type=text/javascript>"; 
    echo "alert('That user doesn't exist. Please try again.')"; 
    echo "</script>"; 
} 
else 
{ 
    //will be code to run if the user does exist 
    echo "<script type=text/javascript>alert('Testing.')</script>"; 
} 
+0

是它寫出$ NUM_ROWS?什麼打印出來了? – Icewine

+0

您的查詢失敗,您需要找出原因;檢查錯誤 –

+0

它寫出$ num_rows,並且查詢正在工作。即使查詢不是,它不會完成else部分嗎? –

回答

0

我無法添加評論。所以我會把它寫成一個答案。

由於您聲明警報JavaScript正在頁面源中顯示,這意味着PHP中的IF/ELSE語句正常工作。問題在於單引號。您在單引號警報功能中有單引號。因此,JavaScript警報功能無法執行。

echo "alert('That user doesn't exist. Please try again.')"; 

嘗試使用這個代替

echo "alert('That user doesn\'t exist. Please try again.');"; 
+0

這確實解決了它。不能相信我錯過了這一點。感謝大家的幫助。 –