使用php从mysql获取数据并显示json输出时为Null输出

时间:2016-10-25 13:30:11

标签: php mysqli sql-injection

大家好,我是PHP的新手,使用带有prepare语句的 json数组输出,但得到null输出。这段代码有什么问题,为什么我得到空输出以及如何解决这个问题。 init.php fil提供了MySQL数据库的连接。

<?php
    require "init.php";
    $post_id = $_POST["pid"];

    if($post_id == ""){

        echo "Empty";

    }else{

        $result = $con->prepare("SELECT * from Posts
                INNER JOIN Users 
                ON Posts.Uid = Users.Uid 
                WHERE Posts.Pid= ? AND Posts.Active = 0)"); 

//查询中的问题是“)”

        $result->bind_param("i", $post_id);
        $result->execute();

        $rows= array();
        while ($row=mysqli_fetch_array($result)) {
            $rows[] = array('post_id'=>$row['Pid'],'user_id'=>$row['Uid'],'post_cat'=>$row['Post_Category'],
                            'user_name'=>$row['User_Name'],'user_profile'=> $row['User_Image'],'post_time'=>$row['Post_Time'],
                            'post_title'=>utf8_encode($row['Post_Title']),'post_desc'=>$row['Post_Desc'],
                            'post_exp'=>$row['Post_Expiry'],'img_link'=>$row['Post_Image'],
                            'post_url'=>$row['Post_Url'],'post_type'=>$row['Post_Type']);
        }
        if (json_encode($rows) == '[]'  || json_encode($rows) == null) {
            echo "No_Post";
        }else{
            echo json_encode(array("post"=>$rows));
        }
        $result->close();

    }
?>

我也在努力使PHP代码安全,但不知道如何?。这段代码可能会出现什么问题。我怎么能让这个安全。在此先感谢。

更新

<?php
    require "init.php";

    $post_id = $_POST["pid"];

        $result = mysqli_query($con,""SELECT * from Posts
                INNER JOIN Users 
                ON Posts.Uid = Users.Uid 
                WHERE Posts.Pid= ? AND Posts.Active = 0");

    $rows= array();
    while ($row=mysqli_fetch_array($result)) {
        $rows[] = array('post_id'=>$row['Pid'],'user_id'=>$row['Uid'],'post_cat'=>$row['Post_Category'],
            'user_name'=>$row['User_Name'],'user_profile'=> $row['User_Image'],'post_time'=>$row['Post_Time'],
            'post_title'=>utf8_encode($row['Post_Title']),'post_desc'=>$row['Post_Desc'],
            'post_exp'=>$row['Post_Expiry'],'img_link'=>$row['Post_Image'],
            'post_url'=>$row['Post_Url'],'post_type'=>$row['Post_Type']);

    }
    if (json_encode($rows) == '[]'  || json_encode($rows) == null) {
        echo "No_Post";
    }else{
        echo json_encode(array("post"=>$rows));
    }

mysqli_close($con);
?>

此代码提供正确的输出,但SQL注入可以在此更新的代码中轻松实现。如何在更新的代码中停止SQL注入?

0 个答案:

没有答案