gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:37:28 25 4
gpt4 key购买 nike

<分区>

我正在使用 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';
}
}
}
?>

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com