首页 > 解决方案 > 您如何做到只有登录用户才能看到他们创建的数据?

问题描述

我正在学习 PHP 和 MySQL,最近决定创建一个小型 Web 应用程序作为测试。该应用程序是一个小型数据库,用户可以在其中跟踪他们当前正在阅读或完成的书籍。

我能够创建一个登录表单,用户必须登录才能访问数据库,但我偶然发现了所有用户都可以访问彼此书籍的问题。我想知道解决此问题的最简单方法是什么?

更新:

添加了索引代码。

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
                <meta http-equiv="x-ua-compatible" content="ie=edge">
                    <!-- Bootstrap CSS -->
                    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
          <!-- jQuery library -->
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
          <!-- Latest compiled JavaScript -->
          <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
          <link rel="stylesheet" href="goals.css" />
<head>
<title>Book Database</title>
</head>

<body>
  <nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Logo</a>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
     <ul class="nav navbar-nav">
       <li class="active"><a href="#">Home</a></li>
       <li><a href="#">Collection</a></li>
     </ul>
     <ul class="nav navbar-nav navbar-right">
        <li><a href="login.php"><span class="glyphicon glyphicon-user"></span> My Account</a></li>
                <li><a href="reset-password.php" class="btn btn-warning">Reset Your Password</a></li>
                <li><a href="logout.php" class="btn btn-danger ml-3">Sign Out of Your Account</a></li>
      </ul>
   </nav>
<div id="container">
  <h1>Book Database</h1>
  <form action="insert_book.php" method="post">
    <label for="bookName">Book</label><br/>
    <input type="text" name="bookName" id="bookName" placeholder="Book name.."></textarea><br/>
    <label for="cat">Category</label><br/>
    <select name="cat" id="cat">
      <option value="0">Fantasy</option>
      <option value="1">Romance</option>
      <option value="2">Biography</option><br/>
    </select>
    <br/><label for="reDate">Release Date</label><br/>
    <input type="date" id="reDate" name="reDate"/><br/>
    <label for="complete">Did you complete this book?</label>
    <input type="checkbox" id="completebook" name="completebook" value="1" /><br/>
    <button type="submit">Submit Book</button>
  </form>
  <?php
  //Adding a php later that inserts the code of another php file here.
  require_once 'connect.php';
  $sql = "SELECT * FROM bookdb";
  $result = mysqli_query($link, $sql) or die(mysqli_error($link));
  print("<h2>Still Reading</h2>");

  //Run this if they still reading the book
  while($row = mysqli_fetch_array($result)){
    if($row['book_complete'] == 0){
      if($row['book_category'] == 0){
        $cat = "Fantasy";
      }elseif ($row['book_category' == 1] ){
        $cat = "Romance";
      }else{
        $cat = "Biography";
      }
      echo "<div class='book'>";
      //when the user hits submit it will send it to the sql database
      echo "<a href='complete.php?id=" . $row['book_id'] . "'><button class='btnComplete'>Completed</button></a><strong>";
      echo $cat . "</strong><p>" . $row['book_name'] ."</p>Released Date: " . $row['book_date'];
      echo "</div>";
    }
  }
  //Completed Books
  print("<h2>Completed books</h2>");
  $result = mysqli_query($link, $sql) or die (mysqli_error($link));
  while($row = mysqli_fetch_array($result)){
    if($row['book_complete'] != 0){
      if($row['book_category'] == 0){
        $cat = "Fantasy";
      } elseif ($row['book_category' == 1]){
        $cat = "Romance";
      } else {
        $cat = "Biography";
      }
      echo "<div class='book'>";
      //when the user hits submit it will send it to the sql database
      echo "<a href='delete.php?id=" . $row['book_id'] . "'><button class='btnDelete'>Delete</button></a><strong>";
      echo $cat . "</strong><p>" . $row['book_name'] ."</p>Released Date: " . $row['book_date'];
      echo "</div>";
    }
  }


  ?>
</div>
</body>

</html>

登录

<?php
// Initialize the session
session_start();

// Check if the user is already logged in, if yes then redirect him to index page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    header("location: index.php");
    exit;
}

// Include config file
require_once "connect.php";

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = $login_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter username.";
    } else{
        $username = trim($_POST["username"]);
    }

    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }

    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT id, username, password FROM users WHERE username = ?";
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);

            // Set parameters
            $param_username = $username;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);

                // Check if username exists, if yes then verify password
                if(mysqli_stmt_num_rows($stmt) == 1){
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                    if(mysqli_stmt_fetch($stmt)){
                        if(password_verify($password, $hashed_password)){
                            // Password is correct, so start a new session
                            session_start();

                            // Store data in session variables
                            $_SESSION["loggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["username"] = $username;

                            // Redirect user to welcome page
                            header("location: index.php");
                        } else{
                            // Password is not valid, display a generic error message
                            $login_err = "Invalid username or password.";
                        }
                    }
                } else{
                    // Username doesn't exist, display a generic error message
                    $login_err = "Invalid username or password.";
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }

    // Close connection
    mysqli_close($link);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        body{ font: 14px sans-serif; }
        .wrapper{ width: 350px; padding: 20px; }
    </style>
</head>
<body>
    <div class="wrapper">
        <h2>Login</h2>
        <p>Please fill in your credentials to login.</p>

        <?php
        if(!empty($login_err)){
            echo '<div class="alert alert-danger">' . $login_err . '</div>';
        }
        ?>

        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="form-group">
                <label>Username</label>
                <input type="text" name="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">
                <span class="invalid-feedback"><?php echo $username_err; ?></span>
            </div>
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
                <span class="invalid-feedback"><?php echo $password_err; ?></span>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Login">
            </div>
            <p>Don't have an account? <a href="register.php">Sign up now</a>.</p>
        </form>
    </div>
</body>
</html>

标签: phpmysql

解决方案


您应该调整您的表架构,以便在插入事务期间会有一个可以接收用户的用户 ID 的可为空字段。


推荐阅读