【发布时间】:2017-05-13 01:54:31
【问题描述】:
我在做一个项目时一直在自学 PHP,所以我的代码可能不是最优雅的,我还在学习。我真的很想稍微清理一下我的代码,并制作一些合理的函数来替换我大量的意大利面条代码。我已经让测试函数正常工作,但是现在我想用一个函数生成我的表,但我遇到了问题并且没有生成错误,这使得调试很麻烦。我有三个文件“functions.php”、“tblDesc.php”和“index.php”,如下所示
index.php:
<html>
<?php
require 'header.php'
?>
<head>
<title>
Asset Manager
</title>
</head>
<body>
<?php
include_once('navBar.php');
?>
<?php
include_once('tblDesc.php');
?>
</body>
functions.php:
<?php
function initTable($query, $tblID){
// Begin Table generation
print "<table id='".$tblID."'> ";
$result = $dbAssetManTest->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
print "<thead>";
print " <tr> ";
// pulls field data for table generation
foreach ($row as $field => $value){
print " <th>$field</th> ";
}
print " </tr> ";
print "</thead>";
// end foreach
//body of Table
print "<tbody>";
// pulls live data from DB
$data = $dbAssetManTest->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr> ";
foreach ($row as $name=>$value){
print " <td>$value</td> ";
} // end field loop
print " </tr> ";
} // end record loop
print "</tbody>";
print "</table>";
}
?>
tblDesc.php
<?php
require "functions.php";
// Begin Table generation
$queryBR="select foo from bar;";
$tblIDBR='tblFooBar';
initTable($queryBR, $tblIDBR);
?>
如果我获取函数initTable 的内容并将initTable($queryBR, $tblIDBR); 行替换为functions.php 中的内容,一切正常,但是;当我尝试将传递给它的函数 vaulues 查询和 tableID 分开时,我的页面在<table id='tblBROnHand'> 处停止加载。
这样可以,但看起来很糟糕:
<?php
// Begin Table generation
$queryBR="select foo from bar;";
$tblID='tblFooBar';
// Begin Table generation
print "<table id='".$tblID."'> ";
$result = $dbAssetManTest->query($queryBR);
$row = $result->fetch(PDO::FETCH_ASSOC);
print "<thead>";
print " <tr> ";
// pulls field data for table generation
foreach ($row as $field => $value){
print " <th>$field</th> ";
}
print " </tr> ";
print "</thead>";
// end foreach
//body of Table
print "<tbody>";
// pulls live data from DB
$data = $dbAssetManTest->query($queryBR);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr> ";
foreach ($row as $name=>$value){
print " <td>$value</td> ";
} // end field loop
print " </tr> ";
} // end record loop
print "</tbody>";
print "</table>";
?>
任何帮助将不胜感激!
【问题讨论】:
-
放入 ini_set('display_errors',1);在文件的开头,或查看 PHP/Apache 错误日志
-
在没有自定义函数的情况下运行您的代码。如果它有效,你会看到需要添加一些东西。这是一个变量范围。
-
我想你会发现这是一个 SCOPE 问题,通常是当你将代码移动到函数中时
-
$dbAssetManTest在函数中不可见,除非您将其作为参数传入 -
我没有看到
$dbAssetManTest定义在你说的代码中也有效
标签: php html dom web-applications