我试图允许用户使用3个下拉框从我的数据库中选择限制。我已经设置好了,我已连接到我的数据库。但是,一旦用户点击提交按钮,我就无法将数据显示在表格中。这是我的代码:
<?php
require_once 'connection.php';
?>
<form action="stats.php" method ="post">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>
Specify Date, Month, and County
</legend>
<p>
<label for="year">
Please select a year
</label>
<select name= 'year'>
<?php
$query = "select distinct year from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
?>
</select>
</p>
<p>
<label for="month">
Please select a month
<label>
<select name= 'month'>
<?php
$query = "select distinct month from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->month."'>".$row->month."</option>";
}
?>
</select>
</p>
<p>
<label for="location">
Please specify a location
</label>
<select name='select'>
<?php
$query = "select * from unemployed";
$result = $conn->query($query);
while ($finfo = $result->fetch_field()) {
echo "<option value='".$finfo->name."'>".$finfo->name."</option>";
}
?>
</select>
</p>
<input type ="submit" />
</fieldset>
</form>
<?php
if (isset($_POST['submitted'])) {
include('connection.php');
$gYear = $_POST["year"];
$gMonth = $_POST["month"];
$gSelect = $_POST["select"];
$query = "select $gSelect from unemployed where year='$gYear' and month='$gMonth'";
$result = $conn->query($query) or die('error getting data');
echo"<table>";
echo "<tr><th>Year</th><th>Time</th><th>$gSelect</th></tr>";
while ($row = $result->fetch_object()){
echo "<tr><td>";
echo $row['Year'];
echo "</td><td>";
echo $row['Month'];
echo "</td><td>";
echo $row['$gSelect'];
echo "</td></tr>";
}
echo "</table";
} // end of main if statement
?>
我根本无法将数据显示在表格中。我尝试了多种方法,但我仍然遇到错误。为了确保我连接到我的数据库,我使用了var_dump($ row)来确保,这样就可以了。所以这不是问题。有谁知道我的代码有什么问题?
答案 0 :(得分:3)
从结果集中检索数据时,您将其作为对象获取:
while ($row = $result->fetch_object()){
但是当你来显示它时,你将它称为数组:
echo "<tr><td>";
echo $row['Year']; // array syntax.
您应该使用对象语法:
echo "<tr><td>";
echo $row->Year; // object syntax.
如果你检查错误日志,你应该看到很多这样的消息。