PHP数组不能以正确的HTML元素打印

时间:2013-10-27 22:50:44

标签: php html arrays mysqli

我已经尝试了10分钟,但找不到办法。我将几个名称放入数据库,并在名为mysqli_fetch_array()的函数中使用sort_member_db()调用这些名称

我在函数中的输出代码是:echo $names['FirstName']. ' ' . $names['LastName']; echo '<br>';

它正确打印所有名称,但名称不在我希望它们所在的div元素中。它们显示在网站的最顶层。

这是我放在div元素中的内容:

 <div class="myclass">
            <hgroup class="title">
                <h1>Text1</h1>
                <h2>
                     text2
                </h2>
            </hgroup>
            <p>
                Array should print after this line:<br>

             '. sort_member_db() .'

            </p>
        </div>

编辑:这是整个功能

function sort_member_db()
{

    $openConn = mysqli_connect(
            "host", "user", "", "");

    //The sorting function for mysql goes here
    $sortedMembers = mysqli_query($openConn, "SELECT * FROM Members ORDER BY LastName");

    //Get the names and insert them into a PHP array
    while($names = mysqli_fetch_array($sortedMembers))
    {
        //Escape sequence to find the possible error
        if (!$sortedMembers)
        {
            printf("Error: %s\n", mysqli_error($openConn));
            exit();
        }

        //Print out the names here        
        echo $names['FirstName']. ' ' . $names['LastName'];
        echo '<br>';
    }

    mysqli_close($openConn);

}

这是我试图将数组放入的div元素:

page_body('        <div id="body">
            <!-- RenderSection("featured", required:=false) -->
            <section class="content-wrapper main-content clear-fix">
                <!-- @RenderBody() -->
                    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>Members:</h1>
                <h2>

                </h2>
            </hgroup>
            <p>
                Our Team Members :<br>

             '. sort_member_db() .'

            </p>
        </div>
            </section>
            </section>');

1 个答案:

答案 0 :(得分:1)

您需要返回并连接HTML中的名称,而不是直接在被调用函数中回显名称,否则将首先执行此操作。

function sort_member_db()
{

    $openConn = mysqli_connect(
            "host", "user", "", "");

    //The sorting function for mysql goes here
    $sortedMembers = mysqli_query($openConn, "SELECT * FROM Members ORDER BY LastName");

    //Get the names and insert them into a PHP array
    $returnString = '';
    while($names = mysqli_fetch_array($sortedMembers))
    {
        //Escape sequence to find the possible error
        if (!$sortedMembers)
        {
            printf("Error: %s\n", mysqli_error($openConn));
            exit();
        }

        //Print out the names here        
        $returnString .= $names['FirstName']. ' ' . $names['LastName'];
        $returnString .='<br>';
    }

    mysqli_close($openConn);
    return $returnString;
}