PHP MySQL注册页面无效

时间:2017-07-22 18:29:37

标签: php mysql mysqli webpage php-5.6

我正在制作一个关于rpi 3的简单网站,我在注册页面遇到了一些麻烦。首先,这是我当前的数据库(id设置为自动增量,名称是用户):

+----+----------+----------+
| id | username | password |
+----+----------+----------+
|  1 | Owner    | idk      |
+----+----------+----------+

我尝试输入用户名:所有者密码:test,同时输出"此用户名已被使用。"它确实出现了问题!",当我测试用户名和密码时,它会提供相同的输出,而不是创建一个帐户。

register.php(主页):

<?php
include("connection.php");
session_start();
if(isset($_SESSION['login_user'])){
   header("Location: welcome.php", true);
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
    $rusername = mysqli_real_escape_string($conn,$_POST['un']);
    $rypassword = mysqli_real_escape_string($conn,$_POST['pw']);

    $sql1 = "SELECT id FROM users WHERE username = '$rusername'";
    $sql2 = "INSERT INTO users(username, password) values($rusername, $rpassword)";

    $result = mysqli_query($conn,$sql1);
    $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
    $count = mysqli_num_rows($result);
    if ($count == 0){
        if (mysqli_query($conn,$sql2)) {
            echo "Account created successfully!";
        } else {
            echo "Something went wrong!";
        }
    } else {
        $error = "This username is already in use.";
    }
}
?>

<html>
    <head>
        <title>Register</title>
        <link rel="stylesheet" href="topbar.css">
    </head>

    <body>
        //Top Bar
        <div class="topbar">
            <a href="index.php">Home</a>
            <a href="login.php">Login</a>
            <a href="register.php">Register</a>
            <a href="about.php">About</a>
        </div>

        //Register Form
        <div align="center">
            <h1>Register</h1>
            <form method="post">
                <h4>Username</h4>
                <input type="text" name="run" required>
                <h4>Password</h4>
                <input type="text" name="rpw" required>
                <br><input type="submit">
            </form>
            <div style="color:#ff0000;"><?php echo $error; ?></div>
        </div>
    </body>
</html>

connection.php:

<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "kellan22";
$databasename = "accounts";

// Create connection
$conn = mysqli_connect($servername, $dbusername, $dbpassword, $databasename);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>

1 个答案:

答案 0 :(得分:1)

您正以错误的方式访问用户输入的数据。那些mysqli_real_escape_string(...)语句应该是这样的:

$rusername = mysqli_real_escape_string($conn,$_POST['run']);
$rpassword = mysqli_real_escape_string($conn,$_POST['rpw']);

另外,在INSERT查询中缺少引号,应该是这样的:

$sql2 = "INSERT INTO `users`(`username`, `password`) values('$rusername', '$rpassword')";

旁注:了解prepared statement,因为您的查询现在容易受到SQL注入攻击。另请参阅how you can prevent SQL injection in PHP