php 5 -> MySQL

Thanks Tutorial!

查找一个用户的全部评论并展示

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <!-- show data from database -->
  <!-- 在 mysql 中查找一个用户的所有评论并将其显示在 search.php 网页上 -->

  <form class="searchform" action="search.php" method="post">
    <label for="search">Search for user:</label>
    <input id="search" type="text" name="userName" placeholder="Search...">
    <button>Search</button>
  </form>

</body>
</html>

search.php

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  
  $userName = $_POST['userName'];
  
  try {
    require_once './includes/dbh.inc.php';

  /* 写法2:named parameters */

    $query2 = "SELECT * FROM comments WHERE username = :username;";

    $stmt2 = $pdo->prepare($query2);

    $stmt2->execute([
      ':username' => $userName,
    ]);

    $result = $stmt2->fetchAll(PDO::FETCH_ASSOC); 
      // 以关联数组的形式返回所有结果,每行数据是一个关联数组,键是列名,值是对应的值

    $stmt2 -> fecth(PDO::FETCH_ASSOC); // 只拿第一个出来,!! 如果什么都没有则返回一个 bool false

    // print_r($result); // 测试输出结果

    unset($stmt2);unset($pdo);

  } catch (PDOException $e) {
    die("Error: " . $e->getMessage());
  }
} 
else {
  header("Location: ../test5.php");
  exit();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <!-- show data from database -->
  <!-- 在 mysql 中查找一个用户的所有评论并将其显示在 search.php 网页上 -->

  <h2 style="color:Yellow"> Search Results <h2>  

  <?php

    if (empty($result)){
      echo "<p>No comments found</p>";
    }
    else {
      foreach ($result as $row) {
        echo htmlspecialchars($row["username"]) . " said: " . htmlspecialchars($row["commentText"]) . " |at " . htmlspecialchars($row["createTime"]);// 别忘了过滤内容!!
        echo "<br>";
      }
    }
  ?>
  
</body>
</html>
posted @ 2026-02-15 19:18  hm2ns  阅读(0)  评论(0)    收藏  举报