的index.php
if (!$result)
{
$error = 'No value found.';
include 'error.html';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$myvalues[] = $row['ValueID'];
}
include 'output.html';
exit();
Output.php
<?php foreach ($myvalues as $allmyvalues): ?>
<?php echo $allmyvalues; ?>
<?php endforeach; ?>
错误是“未定义的变量:myvalues in ... output.php”页面的其余部分显示正确。
使用Apache 2.2.15 / PHP 5.3
知道出了什么问题吗?基本上一切似乎都在运作,但是$ myvalues没有通过。在Windows 2k机器上运行,所以我不认为升级Apache / PHP是一种选择。
提前致谢。
答案 0 :(得分:0)
如果您从上到下阅读代码,您将意识到如果查询中没有返回任何行,那么您的$myvalues
数组永远不会添加任何内容。
PHP可能允许您向未定义的数组添加值,但这本身就是不好的做法。在尝试使用它之前,您应该将数组声明为空(无论是在循环期间还是在您输出结果时)。
在使用变量之前,您还应该检查变量是否存在,尤其是当它们仅是有条件地创建时。
$myvalues = array();
while($row = mysqli_fetch_array($result))
$myvalues[] = $row['ValueID'];
// here, you can use foreach on the array, because you've given it an empty default value
条件定义的一个例子是:
if($foo)
$bar = 'baz';
echo $bar; // could easily be undefined
// You should instead check its existence first
if(isset($bar)) echo $bar;
答案 1 :(得分:0)
你也可以在Output.php
中写下这个:
if(isset($myvalues)) //Check of Existence first, Then Loop it if exists.
{
foreach ($myvalues as $allmyvalues){
echo $allmyvalues;
}
}
但在使用它们之前声明变量$myvalues = array();
始终是最佳做法。
答案 2 :(得分:0)
一个原因可能是您要包含output.html
而不是output.php
,而其他原因可能是您没有将$myvalues
声明为数组。请尝试以下代码
$myvalues=array();
if (!$result)
{
$error = 'No value found.';
include 'error.html';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$myvalues[] = $row['ValueID'];
}
include 'output.php';
exit();
希望这有助于你
答案 3 :(得分:0)
问题在于,如果$result
为false
,则您认为没有找到结果;但是,只有在出现查询错误时才会返回该返回值。空结果集仍被视为成功的查询结果。我建议稍微移动一下逻辑:
$myvalues = array();
if ($result) {
while (($row = mysqli_fetch_array($result)) !== false) {
$myvalues[] = $row['ValueID'];
}
}
if (empty($myvalues)) {
$error = 'No value found.';
include 'error.html';
exit();
}
include 'output.php';