dongmiao520892 2015-08-18 02:21
浏览 35

在单独的PHP函数中,在单独的页面上构建HTML表,调用包含SQL查询的PHP函数?

Basically, I'm trying to organize my code cleaner. I have a bunch of SQL queries which I am storing in a file called Queries.PHP. Example:

//Queries.php

//Connects to Database
$dbh=mysql_connect ("localhost", "~", "~") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("~") or ("Database not found");

function hi3() {
$query = "SELECT AVG(NULLIF(`~`, 0)) FROM `~` WHERE `~` BETWEEN '~' AND '~';";
$result = mysql_query($query) or die ( $result.mysql_error());
$row = mysql_fetch_array($result);
echo "~";

}

Then, on a separate page, I have code that is building HTML table headers and a separate function building the contents:

include Queries.php;

function BuildHTMLTableHeaders {

echo HTML table headers;

BuildHTMLTableBody();

echo </table>;
}

function BuildHTMLBody {

echo <tr>;
echo <td>;
hi3();
echo </td>;
echo </tr>;
...

}

Now, here's my problem: when I call hi3(), the rest of the table doesn't build. Why?

  • 写回答

1条回答 默认 最新

  • donglu3087 2015-08-18 02:37
    关注

    Your logic in BuildHTMLBody is flawed. You're only ever going to echo out 1 table row/cell because you're not looping through the results you get from your function.

    function hi3() {
        $query = "SELECT AVG(NULLIF(`~`, 0)) FROM `~` WHERE `~` BETWEEN '~' AND '~';";
        $result = mysql_query($query) or die ( $result.mysql_error());
        return $result;
    }
    
    function BuildHTMLBody {
        $rows = hi3();
        while($row = mysql_fetch_array($rows)) {
            echo '<tr>';
            echo '<td>' . $row['data'] . '</td>';
            echo '</tr>';
        }
    }
    

    Notice I return the results of hi3() and assign the results to a variable in BuildHTMLBody() and loop through them.

    I haven't tested this, so I'm not sure if there are any syntax errors. Also, I would suggest using mysqli_. mysql_ is deprecated.

    评论

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线