PHP检查数据库中是否存在值

标签 php mysql

<分区>

我正在使用 MySQL,我想检查用户输入的值 $_POST['username'] 是否已经存在于我的数据库中(在字段 username 中).我试过这段代码:

$usernameExists = "SELECT * FROM users WHERE username = " . $_POST['username'];

if ($usernameExists) {
    echo "Exists"
} 

我把这段代码放在 if (!empty...) 语句之后;

但什么也没发生。如果您需要我的完整代码,可以在此处获得,但我认为其余部分不会有帮助:

<?php

session_start();

if (isset($_SESSION['user_id'])) { // user is already logged in
    header("Location: index.php");
}

require('database.php');

$message = '';
$emailMessage = '';
$usernameMessage = '';
$passwordMessage = '';
$confirmMessage = '';

if (!empty($_POST['email']) && !empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['confirmPassword'])) { // user submitted form; enter user

    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $emailMessage = 'Invalid email.';

    } elseif (strlen($_POST['username']) < 4 || strlen($_POST['username']) > 250) {
        $usernameMessage = 'Username has to be between 4 and 250 characters.';

    } elseif (!preg_match("/^[a-zA-z0-9]*$/", $_POST['username'])) {
        $usernameMessage = 'Username can only contain numbers and letters.';

    } elseif (strlen($_POST['password']) < 6 || strlen($_POST['password']) > 250) {
        $passwordMessage = 'Password has to be between 6 and 250 characters.';

    } elseif ($_POST['confirmPassword'] !== $_POST['password']) {
        $confirmMessage = 'Passwords don\'t match THONK';

    } else {
        $sql = "INSERT INTO users (email, username, password) VALUES (:email, :username, :password)";
        $stmt = $conn->prepare($sql);

        $stmt->bindParam(':email', $_POST['email']);
        $stmt->bindParam(':username', $_POST['username']);

        $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
        $stmt->bindParam(':password', $password);

        if ($stmt->execute()) {
            $message = 'Successfully created new user: ' . $_POST['username'];
        } else {
            $message = 'There was an error lol';
        }
    }
}
?>

最佳答案

使用准备好的语句查询数据库。像这样:

 $usernameExists = 0;
 $sql = 'SELECT username FROM users WHERE username = :username';
 $stmt = $conn->prepare($sql);
 $stmt->bindValue(':username',$_POST['username']);
 $stmt->execute();

 if($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // row(s) returned
    $usernameExists = 1;
 } else {
    // no row returned
    $usernameExists = 0;
 }
 $stmt->closeCursor();

然后你可以这样做:

if ($usernameExists) {
   echo "Exists"
} 

关于PHP检查数据库中是否存在值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44685426/

相关文章:

mysql - 我可以使用 SQL 注入(inject)来更改服务器数据库吗?

php - 编写 MySQLI 调用的更好方法

php - proc_open 不在简单的 C 程序上写入 STDIN

php - 如何解决 : The FastCGI process exceeded configured request timeout error: on IIS 7. 5

php - Neo4j PHP Graphaware '400 Bad Content-Type header' 错误

php - 未从 iPhone 接收到 POST 数据

php - 使用 '->where()' 中的数组进行 Laravel 查询构建

php - 在 PHP 中存储用户密码以进行 RESTful API 身份验证

mysql - 在mysql中更新具有相同值的多行

mysql - 超链接可以有多长?