无法从 MySql 数据库获取数据

Not able to get data from MySql database

有一个 php 文件查询 MySql 数据库以获取一些信息,但 else 语句似乎执行任何条件。

require_once("../sqli_connect.php");

$id = $_GET["id"];

$query = "SELECT * FROM post WHERE post_id=".$id;

//echo $query."<br>";

$response = @mysqli_connect($dbc, $query);

if($response){
    $row = $response->fetch_assoc();

    echo "<h2>".$row["post_subject"]."</h2>";
    echo "<h4>".$row["post_by"]."</h4>";
    echo "<div>".$row["post_content"]."</div>";
}
else{
    echo "no response";
}

我什至尝试将查询中的 post_id 更改为常量 ID,例如 1 或 2。

但我还是没看到问题!

提前致谢!

编辑: 不是错误而是错误。

在此处查看此声明,

$response = @mysqli_connect($dbc, $query);

您没有执行查询。应该是,

$response = mysqli_query($dbc, $query);

并使用 mysqli_num_rows() 函数检查它是否 returns 任何行。所以你的代码应该是这样的:

<?php

    require_once("../sqli_connect.php");

    $id = $_GET["id"];
    $query = "SELECT * FROM post WHERE post_id={$id}";

    $response = mysqli_query($dbc, $query);

    if(mysqli_num_rows($response)){
        while($row = $response->fetch_assoc()){
            echo "<h2>".$row["post_subject"]."</h2>";
            echo "<h4>".$row["post_by"]."</h4>";
            echo "<div>".$row["post_content"]."</div>";
        }
    }
    else{
        echo "no response";
    }

?>

相关参考文献如下:

我很感激你现在有了问题的答案,下面的内容与已经接受的内容略有不同,但没有人在这里提到 sql 注入的可能性,所以这可能对你有用一些点。

它对 mysqli 操作使用 OO 方法并利用 prepare statements

/* connection parameters */
$dbhost =   'localhost';
$dbuser =   'root'; 
$dbpwd  =   'xxx'; 
$dbname =   'xxx';  

$conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

if( $conn ){
    /* assuming id is an integer */
    $id=!empty( $_GET['id'] ) ? intval( $_GET['id'] ) : false;

    if( $id ){
        /* set fields to be returned - variables are matched to placeholders `?` */
        $sql='SELECT `post_subject`,`post_by`,`post_content` FROM `post` WHERE `post_id`=?';
        $stmt=$conn->prepare( $sql );

        /* bind user supplied variable in a safe manner */
        $stmt->bind_param('i', $id );
        $res=$stmt->execute();

        if( $res ){
            /* prepare output variables */
            $stmt->bind_result( $subject, $by, $content );

            while( $stmt->fetch() ){/* iterate through recordset */
                echo "
                <h2>{$subject}</h2>
                <h4>{$by}</h4>
                <div>{$content}</div>"; 
            }
        } else {
            echo 'No response'; 
        }
    } else {
        echo 'missing id';  
    }
    $stmt->close();
    $conn->close();
}