dpqmu84646 2012-02-14 01:53
浏览 43

解决方法无法重新声明?

I just finished getting this script working and I need to use it multiple times in the same page. However, when I use it a second time I get the error Fatal error: Cannot redeclare get_names() (previously declared. I looked around for an answer but all I could find was to use the once command but it doesn't seem to work with get. Here is the script:

<?php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
mysql_select_db('dbname', $db);

$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result))
if ($row['pool'] % 2) {
    echo "<h4>Result 1</h4>";
    $names = get_names(1);
    foreach($names as $name) {
        echo $name . "<br/>";
    }
} else {
    echo "<h4>Result 2</h4>";
    $names = get_names(0);
    foreach($names as $name) {
        echo $name . "<br/>";
    }
}

function get_names($pool_result)
{
$name_array = array();

$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {
    array_push($name_array, $row['name']);
}

return $name_array;

} ?>

  • 写回答

4条回答 默认 最新

  • doupu9251 2012-02-14 01:56
    关注

    Put the function definition into it's own file and call include (or require) once at the top of the page on that file.

    get_names is getting defined more than once and so the second time raising a fatal error.

    EDIT:

    The only part that needs to be in it's own file is the function definition:

    function get_names($pool_result)
    {
        $name_array = array();
    
        $query  = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
        $result = mysql_query($query);
    
        while ($row = mysql_fetch_array($result))
            array_push($name_array, $row['name']);
    
        return $name_array;
    }
    

    Though I and surely others would advocate further organization of the code, if you put that function in a file like, library.php or something and then require_once('path/to/library.php') it, you should be able to run the rest of it multiple times.

    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程