gpt4 book ai didi

php - 撤消用户创建,写入数据库

转载 作者:行者123 更新时间:2023-11-30 22:42:50 24 4
gpt4 key购买 nike

这是一个很小的学校项目。我对PHP和SQL非常陌生。我有一个表格,用户可以在其中输入所需的用户名和密码。此后,我试图检查我的数据库,以查看是否存在具有相同用户名的帐户。这是代码:

$sqlValidate = "SELECT id FROM userAccounnts WHERE username='$username'";
$resultValidate = $conn->query($sqlValidate);

$sql = "INSERT INTO userAccounts VALUES($id, '$username', '$password')";

if ($resultValidate != 0) {

$date = new DateTime(); //this returns the current date time
$time = $date->format('d-m-Y-H-i-s');

$sqlErrorLog = "insert into errorLog (errorType, errorTime) values ('Failed to create new user, username already exists', '$time')";
$result = $conn->query($sqlErrorLog);

echo '<script type="text/javascript">'
, 'alert("Sorry,an account with that Username already exists. Please choose another one.");
window.location.href = "user.php";'
, '</script>'
;
}


首先,我查询数据库。这样做的目的是检查用户名等于从表单传递的用户名时是否存在 id。此后,我使用 if语句检查是否 id不等于0(以查看是否存在这样的ID)。如果是这样,我将错误日志写入数据库。

该代码不起作用。它将完全忽略if语句,并将新用户帐户写入数据库。在此先感谢您的帮助。只要代码有效,我都不介意代码是否安全。

PS,此 else语句没有 if语句。

最佳答案

最后,我决定采用这种方法:

<?php
$id=10001;
$sql = "SELECT id FROM userAccounts ORDER BY id DESC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$id = $row["id"] + 1;
}

$username = $_REQUEST["emailInput"];
$password = $_REQUEST["passwordInput"];

//the following query is used to check if a username with the same
//name as the username entered by the user already exists
$sqlValidate = "SELECT id FROM userAccounts WHERE username='$username'";


$result = $conn->query($sqlValidate); //running the query

//if the query returns results, the error will be inserted into the DB using the following code:
if ($result->num_rows > 0) {

$date = new DateTime(); //this returns the current date time
$time = $date->format('d-m-Y-H-i-s');

//the following code queries the DB
$sqlErrorLog = "insert into errorLog (errorType, errorTime) values ('Failed to create new user, username already exists', '$time')";
$result = $conn->query($sqlErrorLog);

echo '<script type="text/javascript">'
, 'alert("Sorry,an account with that Username already exists. Please choose another one.");
window.location.href = "user.php";'
, '</script>'
;
return;
}


因此,我查看是否存在具有相同用户名的 id。如果查询返回结果(如果是具有此类用户名的行),则它将撤销该请求,将其写入数据库,并发出JavaScript警报以通知用户。它运行良好,并成功写入数据库。

关于php - 撤消用户创建,写入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30641438/

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