-2

我有一个页面显示来自我的数据库的信息。每个数组都有一个编辑链接,该链接具有一个统一的 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>
4

1 回答 1

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();
于 2012-05-28T18:02:08.390 回答