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

时间:2017-06-21 20:10:24

标签: 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';
        }
    }
}
?>

1 个答案:

答案 0 :(得分:3)

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

 $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"
}