while循环中的PHP错误帮助

时间:2014-11-14 22:36:21

标签: php blogs fatal-error

我无法弄清楚如何解决PHP错误。

在下面的代码中,我收到错误:

致命错误:无法重新声明getintro()(先前在第94行声明...)

我在下面标记了第94行。任何帮助或指导表示赞赏。我的目标是根据数据库的每一行循环显示每篇博文,只显示部分文本。当它点击它的链接时,它应该在blog.php

中打开包含评论的完整博客
    <?php   // retreive post
     include('php/config.php');
    include ('php/function.php');
    dbConnect();

    $blog_query = mysql_query(
    'SELECT * 
    FROM Blog
    ORDER BY DATE DESC');

    while($row = mysql_fetch_array($blog_query)):

    $date = date_create($row['DATE']);
    $str = $row['CONTENT'];
    $ID = $row['ID'];

LINE 94    function getIntro($str, $count = 200) {
        return preg_replace('/\s+?(\S+)?$/', '', substr(nl2br($str), 0, $count)) . "   <a href=\"blog.php?page={$ID}\" class=\"changeColor\">Read more...</a>\n";
        }
        $new_string = getIntro($str);
    ?>

    <div class="post">
        <h2><?php echo $row['TITLE']?></h2>
        <h3><?php echo date_format($date, 'l, F j, Y')?></h3>
        <p><?php echo $new_string?></p>
    </div>

</div>      
<?php endwhile?>    

4 个答案:

答案 0 :(得分:2)

您的函数正在循环中声明。将函数声明移到循环之外。

    <?php   // retreive post
     include('php/config.php');
    include ('php/function.php');
    dbConnect();

    $blog_query = mysql_query(
    'SELECT * 
    FROM Blog
    ORDER BY DATE DESC');

    function getIntro($str, $count = 200) {
        return preg_replace('/\s+?(\S+)?$/', '', substr(nl2br($str), 0, $count)) . "   <a href=\"blog.php?page={$ID}\" class=\"changeColor\">Read more...</a>\n";
    }

    while($row = mysql_fetch_array($blog_query)):

    $date = date_create($row['DATE']);
    $str = $row['CONTENT'];
    $ID = $row['ID'];

    $new_string = getIntro($str);
    ?>

    <div class="post">
        <h2><?php echo $row['TITLE']?></h2>
        <h3><?php echo date_format($date, 'l, F j, Y')?></h3>
        <p><?php echo $new_string?></p>
    </div>

</div>      
<?php endwhile?>    

答案 1 :(得分:2)

您在循环中声明一个函数,因此每次迭代它都会重新声明导致该问题的相同函数。我会在循环上面声​​明函数并在循环中调用函数。

答案 2 :(得分:0)

将你的函数声明带出while循环! (声明必须在你使用它之前!)

function getIntro($str, $count = 200) {
        return preg_replace('/\s+?(\S+)?$/', '', substr(nl2br($str), 0, $count)) . "   <a href=\"blog.php?page={$ID}\" class=\"changeColor\">Read more...</a>\n";
        }

答案 3 :(得分:0)

将函数定义移出循环,例如将它放在dbConnect:

之前
function getIntro($str, $count = 200) {
        return preg_replace('/\s+?(\S+)?$/', '', substr(nl2br($str), 0, $count)) . "   <a href=\"blog.php?page={$ID}\" class=\"changeColor\">Read more...</a>\n";
        }
相关问题