如何检查MySQL的页面是否为空?

时间:2013-02-03 01:14:51

标签: php mysql content-management-system blogs

我又回来了,试图创建一个“自定义”的博客系统。或者CMS,就像人们所说的那样。这是我目前的代码:

<?php
//include stuff here
$pid = $_GET['pageid'];
$data = mysql_query("SELECT * FROM entries WHERE id='$pid'") or die("MySQL died.");
mysql_real_escape_string($pid);
while($info = mysql_fetch_array( $data )) 
{
if (!empty($info)) {
echo $info['data'];
}
else {
echo 'This page no existo.';
}
}
?>

发生的事情是它没有显示“此页面没有存在”。作为'404'文本。 让我们说有人试图直接输入我的网站但是犯了一个错误: 本地主机/博客/?的pageid = 10 它没有显示404文本!

我在MySQL中有一行名为“data”的行。它由博客文章的 - 嗯...数据组成。我还有一行名为ID的行,它是一个自动增量ID系统。 “真正的”工作页面ID为1。

谢谢, RBLXDev。

编辑: $ info的Vardump: vardump:

array (size=10)
0 => string '1' (length=1)
'id' => string '1' (length=1)
1 => string 'Testing potatoCMS... and the title.' (length=35)
'title' => string 'Testing potatoCMS... and the title.' (length=35)
2 => string 'This is a test.
This is a new line.
This is a cookie.
You are getting fat.
FAT.<br />lol' (length=88)
'data' => string 'This is a test.
This is a new line.
This is a cookie.
You are getting fat.
FAT.<br />lol' (length=88)
3 => string '2013-02-02' (length=10)
'date' => string '2013-02-02' (length=10)
4 => string 'Unspecified' (length=11)
'author' => string 'Unspecified' (length=11)

是的,嗯......我有很奇怪的占位符。

3 个答案:

答案 0 :(得分:1)

我尝试这样的事情......

<?php

        $pid = $_GET['pageid'];
        mysql_real_escape_string($pid);

        $data = mysql_query("SELECT * FROM entries WHERE id='$pid'") or die("MySQL died.");

        $num_rows = mysql_num_rows($data);

        if ($num_rows == NULL) {

              echo 'This page no existo.';

        } else {

                  $info = mysql_fetch_array( $data );
                  echo $info['data'];
        }
?>

未经测试

已更新!

答案 1 :(得分:1)

首先,让我们从你来到这里开始:

如果记录不存在,mysql_fetch_array( $data )将返回false,因此,它甚至不再进入while块。所以,你的逻辑错了。

其次,您使用mysql_real_escape_string()错误。您需要在执行SQL查询之前调用它,并且需要在要注入SQL查询的变量中捕获其输出:

$pid = mysql_real_escape_string($pid);
$data = mysql_query("SELECT * FROM entries WHERE id='$pid'") or die("MySQL died.");

第三,您可能想要考虑完全抛弃mysql_*函数,因为该库正在被弃用,因为它提供了很差的缓解SQL注入的能力。请考虑使用改进的mysqli_*库函数或PDO

答案 2 :(得分:0)

  1. Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO,here is a good tutorial

  2. 在在查询中使用 之前,您必须转义数据

  3. mysql_num_rows()是判断您的查询是否有任何结果的最佳方式。

  4. 如果您只想要查询中的一行,则无需遍历所有结果。

  5. 如果$_GET['pageid']始终是一个数字,您应该cast it to an integer以减少SQL注入的机会

  6. <?php
    //include stuff here
    $pid = $_GET['pageid'];
    mysql_real_escape_string($pid);
    $data = mysql_query("SELECT * FROM entries WHERE id='$pid'") or die("MySQL died.");
    if (mysql_num_rows() > 0) {
    
        $info = mysql_fetch_array( $data );
        echo $info['data'];
    }
    else {
        echo 'This page no existo.';
    }
    ?>