这是一个非常小的学校项目。我对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
语句。
答案 0 :(得分:0)
最后我决定采用这种方法:
<?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警报以通知用户。它运行良好并成功写入数据库。