[英]Can't display data from my database
我試圖通過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)進行確認,並且工作正常。 因此,這不是問題。 有人知道我的代碼有什么問題嗎?
從結果集中檢索數據時,您將其作為對象來獲取:
while ($row = $result->fetch_object()){
但是,當您顯示它時,您將其稱為數組:
echo "<tr><td>";
echo $row['Year']; // array syntax.
您應該使用對象語法:
echo "<tr><td>";
echo $row->Year; // object syntax.
如果您檢查錯誤日志,應該會看到很多有關此結果的消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.