为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 ?在网址中?

如何使用 ?在网址中?

PHP
摇曳的蔷薇 2023-08-19 14:28:40
我正在尝试找出一种方法,让一个 PHP 页面显示我的所有博客文章,但让 URL 决定从该数据库请求什么文章。有点像这样:localhost/bolg/posts.php?pid=1在我的数据库中,我将其设置为每个帖子都有一个与之关联的 ID。所以我想要的是将 pid=1 并将其放入 MySQL 代码中。这是 post.php 的 PHP 代码<?php$servername = "localhost";$username = "root";$password = "";$dbname = "test";// Create connection$conn = new mysqli($servername, $username, $password, $dbname);// Check connectionif ($conn->connect_error) {    die("Connection failed: " . $conn->connect_error);}$sql = "SELECT id, title, content, date FROM posts where id =3";$result = $conn->query($sql);if ($result->num_rows > 0) {    // output data of each row    while($row = $result->fetch_assoc()) {        echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";    }} else {    echo "0 results";}$conn->close();?>
查看完整描述

1 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

example.com?pid=10假设您在浏览器地址栏中输入,您可以pid使用$_GET数组捕获该变量,当使用查询字符串调用页面时,PHP 会自动为您填充该变量。


使用现有代码作为起点,您可以


<?php


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "test";


if (isset($_GET['pid'])) {

    // Create connection

    $conn = new mysqli($servername, $username, $password, $dbname);

    

    $sql = "SELECT id, title, content, date FROM posts where id = ?";

    $stmt = $conn->prepare($sql);

    $stmt->bind_param('i', $_GET['pid']);

    $stmt->execute();


    $result = $stmt->get_result();


    if ($result->num_rows > 0) {

        // output data of each row

        // while looop is not necessary, you are only returning one row

        $row = $result->fetch_assoc();

        echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";

    }

    $conn->close();

} else {

    echo "0 results";

}



查看完整回答
反对 回复 2023-08-19
  • 1 回答
  • 0 关注
  • 59 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信