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

标签 php mysql sql web

这是一个很小的学校项目。我对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/

相关文章:

java - 安卓,http : How to upload a file to a site hosted by a shared server?

php - 我试图让我的 "Details"页面引用我的服务器的两个独立部分,它们通过 techID 链接

mysql - 如何在mysql中使用函数uuid()设置默认值?

php - SQL 查询按时间戳分组和排序

php - 具有日期时间的 Symfony 实体

php - 如何使用 xdebug 查找 php 内存泄漏?

php - mysql 使用触发器更新另一个表

mysql - 不同 SQL 平台中的 ALL 子句

sql - 如果不存在则插入两个表的总和

sql - 在 PostgreSQL 中插入带单引号的文本