如何使用 ?在网址中?

我正在尝试找出一种方法,让一个 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 connection

if ($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();

?>


摇曳的蔷薇
浏览 62回答 1
1回答

蓝山帝景

example.com?pid=10假设您在浏览器地址栏中输入,您可以pid使用$_GET数组捕获该变量,当使用查询字符串调用页面时,PHP 会自动为您填充该变量。使用现有代码作为起点,您可以<?phpmysqli_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";}
打开App,查看更多内容
随时随地看视频慕课网APP