如何检查数据库表中是否存在用户?

时间:2013-11-14 13:02:53

标签: mysql database username exists

我试图找出当前登录的用户是否存在于某个数据库表中。如果它们已经存在,则给出错误。如果他们不这样做,我需要将用户名和表单数据添加到表中。我是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";
}

?>
像我说的那样,我才刚刚开始。当我考虑我需要采取的步骤时,一切都有意义,但代码不起作用。我坚持的主要部分是检查用户是否存在。有什么建议吗?

1 个答案:

答案 0 :(得分: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);
?>