2013-11-14 207 views
0

我想知道當前登錄的用戶是否存在於某個數據庫表中。如果它們已經存在,請給出錯誤。如果他們沒有,我需要將用戶名和表單數據添加到表中。我是PHP和MySQL數據庫的新手。這裏是我到目前爲止的代碼:如何檢查用戶是否存在於數據庫表中?

//my HTML form, pretty simple. 
<form method="post" action=""> 
<p>Out of Office <input name="onoff" type="checkbox" value="ON"></p> 

<p><label>Custom Out of Office Message</label> 
<input type="text" name="custommessage" size="30" maxlength="25"/></p> 

<p><label>Enter Username</label> 
<input type="text" name="username" size="30" maxlength="25"/></p> 

<p><input type="submit" name="submit" value="Submit" /></p> 
</form> 

<?php 
//I figured if I get the user information from the "b83hi_users" table, I can check it against the field input for "username" in the form above. 

$user = JFactory::getUser(); 

if ($user->username == $_POST['username']) { 

    //This checks if the checkbox is marked ON(or off). If it is checked (ON), I want to insert the form data into a table b83hi_out_of_office. 
    if ($_POST['onoff'] == 'ON'){ 

    $sql = "INSERT INTO b83hi_out_of_office (username, custommessage) VALUES ('$_POST[username]'.'$_POST[custommessage]')"; 
} 

}

else{ 
    echo "Invalid Username"; 
} 

?> 

就像我說的,我剛剛開始。當我想到需要採取的步驟時,一切都很有意義,但代碼無法正常工作。我堅持的主要部分是檢查用戶是否存在。有什麼建議麼?

回答

0

要檢查用戶是否在數據庫中存在,您需要連接到數據庫第一:

<?php 
$conn = mysqli_connect($hostname,$dbUsername,$dbPass,$dbName); 

$checkQuery = SELECT * from b83hi_users WHERE username='$_POST[username]'; 

$userCheck = mysqli_query($conn, $checkQuery); 

if(!$userCheck){ 
echo "Invalid Username"; 
} 
mysqli_close($conn); 
?> 
+0

我並不需要包括因爲我在使用的Joomla巫師連接到數據庫的一部分,它會自動連接爲了我。 我試過這段代碼,但是當我去看我的網站上的頁面時,它只是簡單的白色和空白。這是什麼原因? – user2647160

+0

我編輯了$ checkQuery,我在那裏犯了一個錯誤。再試一次,讓我知道。 –

+0

你需要在$ userCheck =行的結尾添加一個分號 - 我無法進行編輯,因爲它需要6個字符長,這只是1,所以它落在裂縫之間...... – bhttoan

相關問題