通过 PHP 连接 mySQL 数据库

Connecting mySQL db through PHP

首先让我说我在这方面非常陌生。我正在尝试开发一个没有实际经验的移动应用程序和网站。可能有什么我错过了或者我做错了,但我似乎无法指出问题出在哪里。在创建我自己的之前,我遵循了视频指南(演示文件已下载到我的计算机),但似乎无法连接到我的数据库。我还复制了演示文件并将它们放入我的代码中,但它仍然让我陷入困境。我正在使用程序 MAMP 进行连接,使用 Brackets 进行代码。以下是我的会话文件:

数据库连接-

<?php

$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "Login System";

$con = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

我的报名文件-

<?php

if (isset($_POST['submit'])) {

    include_once 'dbh.inc.php';

    $first = mysqli_real_escape_string($conn, $_POST['first']);
    $last = mysqli_real_escape_string($conn, $_POST['last']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $uid = mysqli_real_escape_string($conn, $_POST['uid']);
    $pwd = mysqli_real_escape_string($conn, $_POST['pwd']);

    //Error handlers
    //Check for empty fields
    if (empty($first) || empty($last) || empty($email) || empty($uid) || empty($pwd)) {
        echo <h2>Please fill in all fields;
        exit ();
    } else {
        //Check if input characters are valid
        if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
            header("Location: ../signup.php?signup=invalid");
            exit();
        } else {
            //Check if email is valid
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                header("Location: ../signup.php?signup=email");
                exit();
            } else {
                $sql = "SELECT * FROM users WHERE user_uid='$uid'";
                $result = mysqli_query($conn, $sql);
                $resultCheck = mysqli_num_rows($result);

                if ($resultCheck > 0) {
                    header("Location: ../signup.php?signup=usertaken");
                    exit();
                } else {
                    //Hashing the password
                    $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
                    //Insert the user into the database
                    $sql = "INSERT INTO users (first, last, email, uid, pwd) VALUES ('$first', '$last', '$email', '$uid', '$hashedPwd');";
                    mysqli_query($conn, $sql);
                    header("Location: ../signup.php?signup=success");
                    exit();
                }
            }
        }
    }

} else {
    header("Location: ../signup.php");
    exit();
}

?>

我的登录Sheet

    <?php
    include_once 'header.php';
?>

    <section class="main-container">
        <div class="main-wrapper">
            <h2>Signup</h2>
            <form class="signup-form" action="includes/signup.inc.php" method="POST">
                <input type="text" name="first" placeholder="Firstname">
                <input type="text" name="last" placeholder="Lastname">
                <input type="text" name="email" placeholder="E-mail">
                <input type="text" name="uid" placeholder="Username">
                <input type="password" name="pwd" placeholder="Password">
                <Button type="submit" name="submit">Sign up</Button>
            </form>

        </div>
    </section>

<?php
    include_once 'footer.php';
?>

我已将 'root' 的密码重置为 'root' 并确保我可以用它登录。如果任何字段为空,则检查错误列表的文档,return 到 url 中带有单词“=empty”的上一页。无论我在我的字段中键入什么,要么没有将信息推送到数据库中,要么我错误地映射了我的字段,因此其中一个数据库字段为空。

如有任何帮助,我们将不胜感激。正如我在本文开头所说 post,我对此非常陌生。您可能会看到一些非常明显但有些愚蠢的东西……您已经被警告过!我正在创建一个允许用户登录的移动应用程序和网站。登录尝试将引用我的 localhost 数据库以确认用户不存在或用户未在使用中。

谢谢!

要检查连接处理,您可以在连接尝试后添加:

$conn = mysqli_connect( ... );

if ( !$conn ) {
    die( 'Did not connect: ' . mysqli_connect_error() ); 
}

要检查查询后的处理,您可以在查询尝试后添加:

$result = mysqli_query( $conn, $sql );

if (false === $result) {
    die( 'Query error: ' . mysqli_error($conn) );
}

立即使用 php -l 我发现 includes/signup.inc.php 文件中的代码存在一些错误。

echo <h2>Please fill in all fields; 行未被引用,当我尝试加载页面时会导致错误 500。为了解决这个问题,我添加了单引号 echo '<h2>Please fill in all fields</h2>'; 并添加了 </h2> 来关闭 HTML 标签。

修复后页面将 return Please fill in all fields 即使我已经填写了注册表中的所有字段。为了解决这个问题,我将 mysqli_real_escape_string($conn, $_POST['POST_DATA']); 更改为 strip_tags(trim($_POST['POST_DATA']));

电子邮件行有点不同,mysqli_real_escape_string($conn, $_POST['email']); 更改为 filter_var(trim($_POST['email'], FILTER_SANITIZE_EMAIL));

我还更改了 $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);(PHP 文档:http://php.net/manual/en/function.password-hash.php)行以添加盐。什么是盐?

In cryptography, a salt is random data that is used as an additional input to a one-way function that "hashes" a password or passphrase. Salts are closely related to the concept of nonce. The primary function of salts is to defend against dictionary attacks or against its hashed equivalent, a pre-computed rainbow table attack.

来源:en.wikipedia.org/wiki/Salt_(密码学)
另请查看 stackexchange/security 中的 post 以获取更多信息 Link:https://security.stackexchange.com/a/51983



新建 includes/signup.inc.php 文件

<?php
if (isset($_POST['submit'])) {
  include_once 'dbh.inc.php';
  $first = strip_tags(trim($_POST['first']));
  $last = strip_tags(trim($_POST['last']));
  $email = filter_var(trim($_POST['email'], FILTER_SANITIZE_EMAIL));
  $uid = strip_tags(trim($_POST['uid']));
  $pwd = strip_tags(trim($_POST['pwd']));
  //Error handlers
  //Check for empty fields
  if (empty($first) || empty($last) || empty($email) || empty($uid) || empty($pwd)) {
    echo '<h2>Please fill in all fields</h2>'; // was echo <h2>Please fill in all fields; which would cause an error 500
    exit ();
  }
  else {
    //Check if input characters are valid
    if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
      header("Location: ../signup.php?signup=invalid");
      exit();
    }
    else {
      //Check if email is valid
      if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        header("Location: ../signup.php?signup=email");
        exit();
      }
      else {
        $sql = "SELECT * FROM users WHERE user_uid='$uid'";
        $result = mysqli_query($conn, $sql);
        $resultCheck = mysqli_num_rows($result);
        if ($resultCheck > 0) {
          header("Location: ../signup.php?signup=usertaken");
          exit();
        }
        else {
          //Hashing the password
          $options = [
            'cost' => 12,
          ];
          $hashedPwd = password_hash($password, PASSWORD_BCRYPT, $options); // Adding salt to hashed password
          //Insert the user into the database
          $sql = "
                    INSERT INTO users (first, last, email, uid, pwd)
                    VALUES ('" . $first . "', 
                    '" . $last . "', 
                    '" . $email . "', 
                    '" . $uid . "', 
                    '" . $hashedPwd . "');";
          mysqli_query($conn, $sql);
          header("Location: ../signup.php?signup=success");
          exit();
        }
      }
    }
  }
}
else {
  header("Location: ../signup.php");
  exit();
}
?>


此外,最好学习如何使用 mysqli 的 OOP 样式来执行更复杂的数据库操作
PHP mysqli 文档:php.net/manual/en/mysqli.query.php
最好添加一列作为序列号,以便以后使用此 MySQL 查询为用户编辑值:

ALTER TABLE `users` ADD `serial` INT PRIMARY KEY AUTO_INCREMENT;