来自url的$ _GET id仅显示来自数据库PHP mySQL的第一条记录

时间:2014-08-16 08:50:11

标签: php mysql get

我想从url" /view.php获取id?postID = 2",有这段代码:

$post = "SELECT * FROM news WHERE postID='$postID'";
$post1 = mysql_query($post);
$postV = mysql_fetch_array($post1);
$postID = $postV['postID'];
$postImg = $postV['img'];
$postTitle = $postV['title'];
$postAuthor = $postV['author'];
$postDate = $postV['date'];
$postCategory = $postV['category'];
$postText = $postV['text'];


<?php
if (isset($_GET['postID'])) {
    $newsID = $_GET['postID'];
}

echo "<section class='view_news'>
    <img class='view_newsimg' src='$postImg'>
    <h3 class='lath'>$postTitle</h3>
    <ul class='det'>
        <li class='adc'>avtori: $postAuthor</li>
        <li class='adc'>TariRi: $postDate</li>
        <li class='adc'>kategoria: $postCategory</li>
    </ul>
    <p class='news'>
        $postText
    </p>
</section>";
?>

但它只显示postID = 1

的数组中的数据 谁能告诉我该怎么办?谢谢:))

3 个答案:

答案 0 :(得分:1)

这里有三件事是错的:

  1. 您需要先使用$ _GET

    获取postID值

    $ post =“SELECT * FROM news WHERE postID ='{$ _ GET ['$ postID']}”;

  2. 你应该使用while循环

    while($ postV = mysql_fetch_array($ post1)){

    $ postID = $ postV ['postID'];

    $ postImg = $ postV ['img'];

    $ postTitle = $ postV ['title'];

    $ postAuthor = $ postV ['author'];

    $ postDate = $ postV ['date'];

    $ postCategory = $ postV ['category']; $ postText = $ postV ['text']; }

  3. 您的代码可以使用SQL注入,使用mysql_real_escape_string()来阻止它。

答案 1 :(得分:0)

改变这个:

$post = "SELECT * FROM news WHERE postID='$postID'";

与此:

$post = "SELECT * FROM news WHERE postID='{$_GET['postID']}'";

答案 2 :(得分:0)

这里有三件事你做错了。首先,在设置mysql_query()之前运行$postID,另一个是您没有使用While循环。第三件事是你启动php两次<?php。尝试设置$postID并使用while循环。您的代码应如下所示

    <?php
$postID="Your Value";
            post = "SELECT * FROM news WHERE postID='$postID'";
            $post1 = mysql_query($post);
    while($postV = mysql_fetch_array($post1){

            $postID = $postV['postID'];
            $postImg = $postV['img'];
            $postTitle = $postV['title'];
            $postAuthor = $postV['author'];
            $postDate = $postV['date'];
            $postCategory = $postV['category'];
            $postText = $postV['text'];
            }


            if (isset($_GET['postID'])) {
                $newsID = $_GET['postID'];
            }

            echo "<section class='view_news'>
                <img class='view_newsimg' src='$postImg'>
                <h3 class='lath'>$postTitle</h3>
                <ul class='det'>
                    <li class='adc'>avtori: $postAuthor</li>
                    <li class='adc'>TariRi: $postDate</li>
                    <li class='adc'>kategoria: $postCategory</li>
                </ul>
                <p class='news'>
                    $postText
                </p>
            </section>";
            ?>

希望这有助于你