【问题标题】:How do you check if a user exists in a database table?如何检查用户是否存在于数据库表中?
【发布时间】:2013-11-14 13:02:52
【问题描述】:

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

?>

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

【问题讨论】:

    标签: mysql database exists


    【解决方案1】:

    要检查用户是否存在于数据库中,你需要先连接到数据库:

    <?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);
    ?>
    

    【讨论】:

    • 我不需要包含连接到数据库的部分,因为我在 Joomla 中使用了 sorcerer,它会自动为我连接。我尝试了这段代码,但是当我去查看我网站上的页面时,它只是纯白色和空白。这是什么原因造成的?
    • 我编辑了 $checkQuery,我在那里犯了一个错误。再试一次,让我知道。
    • 您需要在 $userCheck= 行的末尾添加一个分号 - 我无法进行编辑,因为它需要 6 个字符长,而这只有 1 个,所以它介于裂缝之间。 .
    • 已修复@bhttoan感谢您的提醒
    • @SabTheCoder 我仍然只是得到一个空白页...另外,我想知道... b83hi_ 是我数据库中所有表的前缀,是否有必要在在代码中命名表?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 2021-12-28
    • 2015-02-02
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多