我有一个显示数据库信息的页面。每个数组都有一个具有unic id的编辑链接(.html?id = 4)。
问题: 我创建的用于根据id查询数据库的表单导致没有显示信息?
知道我需要做些什么来实现这个目标吗?
<?php
// Connect to the database
require 'include/episodelist.db.php';
// Ask the database for the information from the table based on .html?id=#
$query="SELECT * FROM `season` WHERE `id` = $id";
//The above query is the problem.
$result = mysql_query("SELECT * FROM 'season'");
mysql_close();
?>
<form action="include/epslist.edit.php" method="POST">
<table>
<tr>
<td>Season Number: </td><td><input type="text" name="season_sum" size="50" value="<?php echo "$season_num";?>"></td>
</tr>
<tr>
<td>Episode Number: </td><td><input type="text" name="eps_num" size="50" value="<?php echo "$eps_num";?>"></td>
</tr>
<tr>
<td>Temp Episode Number: </td><td><input type="text" name="temp_eps_num" size="50" value="<?php echo "$temp_eps_num";?>"></td>
</tr>
<tr>
<td>Title: </td><td><input type="text" name="title" size="50" value="<?php echo "$title";?>"></td>
</tr>
<tr>
<td>Description: </td><td><textarea type="text" name="descrip" cols="50" rows="7" value="<?php echo "$descrip";?>"></textarea></td>
</tr>
<tr>
<td colspan="2">
<input type="Submit" value="Update">
</td>
</tr>
</table></form>
答案 0 :(得分:1)
您需要检查表单是否将$ id作为变量传递,如果是,请获取$ id并使用数据库中的数据填充字段。如果没有,请显示空白表格。
<?php
if(isset($_GET['id']))
{
// Get ID
$id = mysql_real_escape_string($_GET['id']);
// Do query and save data to array
$query="SELECT * FROM `season` WHERE `id` = $id";
$result = mysql_query("SELECT * FROM 'season'");
$row = mysql_fetch_assoc($result);
$fields = array('seasonid' => $row['seasonid'],
'episodenum' => $row['episodenum']
);
mysql_close();
}
else
{
// No id, use blank values
$fields = array('seasonid' => '',
'episodenum' => ''
);
}
?>
<!-- Populate form with fields array -->
...
<td>Season Number: </td><td><input type="text" name="season_sum" size="50" value="<?php echo($fields['seasonid']); ?>"></td>
...
当然,以这种方式使用mysql会带来安全问题,并且正朝着弃用的方向发展。 PDO(PHP数据对象)是处理数据库操作的方法。 PDO的使用允许预处理语句/参数化查询,看起来像这样:
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$id = $_GET['id'];
// Use a prepared statement to avoid SQL injection
$sth = $dbh->prepare('SELECT * FROM `season` WHERE `id` = :id');
$sth->bindValue(':id', $id, PDO::PARAM_INT);
$sth->execute();