【问题标题】:Function does not stay within wrapper函数不在包装器内
【发布时间】:2014-12-09 14:49:09
【问题描述】:

我有一个运行查询并从MySqldatabase 提取数据的函数。但是,当我运行查询时,它不会停留在 div 内,但如果我执行 $content2 = 'test' 之类的操作,它就可以工作。下面是我的PhP 代码和CSS

function runquery()
{
$connect = mysqli_connect('localhost', 'root', 'password', 'data');
$per_page = 6;
$query = mysqli_query($connect, 'SELECT cid, fname, lname,address, score  FROM customers');
while ($query_row = mysqli_fetch_assoc($query)) {
    echo $query_row['fname'] . '<br />';
}
$content2 = runquery();
}
include 'templates.php';

这里是 Templates.php

<div id="content_area">
     <?php echo $content; ?>
     </div>
 <div id="content_area2">
     <?php echo $content2; ?>
 </div>

还有 CSS:

#content_area
{
float: left;
width: 750px;
margin: 20px 0 20px 0;
padding: 10px;
}
#content_area2
{
float: left;
width: 750px;
margin: 20px 0 20px 0;
padding: 10px;
}

【问题讨论】:

  • 你能解释一下你的观察吗?浮动时可能只是 CSS 宽度太大。是否尝试过调整 CSS,或将其停用以查看发生了什么?
  • 那是因为$content2 = runquery(); 导致我的朋友无限循环。递归永远不会结束
  • 我明白了!谢谢杰,我想已经很晚了哈哈

标签: php html mysql css


【解决方案1】:

您的函数需要在 while() 循环中使用 return 而不是 echo

function runquery() {
        $connect = mysqli_connect('localhost', 'root', 'password', 'data');
        $per_page = 6;
        $query = mysqli_query($connect, 'SELECT cid, fname, lname,address, score  FROM customers');
        while ($query_row = mysqli_fetch_assoc($query)) {
               $array[] = $query_row['fname'] . '<br />';
            }

        // Return
        return $array;
    }

// You assign the content outside the function.
$content2 = implode("",runquery());

【讨论】:

  • 太棒了!完美地工作。我不敢相信我没有看到。再次感谢您的快速回复!
  • 没问题!有时最简单的事情是最容易错过的。
猜你喜欢
  • 2011-06-25
  • 2023-03-19
  • 2018-10-16
  • 2017-09-13
  • 2023-03-16
  • 1970-01-01
  • 2021-02-27
  • 2021-04-06
  • 2017-11-05
相关资源
最近更新 更多