当试图在PHP中创建一个表的编辑页面时,我在edit.php页面遇到问题,当我点击编辑表格行按钮时,它显然会将我带到正确的页面(编辑.php),然后当我输入已编辑的详细信息并提交它时,它会创建一个全新的表行条目,而不是更新我选择要更新的那个。
我已经检查过以确保将id正确设置为数据库中正确的表行,并且确实如此。我不知道为什么会这样做。任何帮助将不胜感激。
<?php require("manage_post.php"); ?>
<?php
session_start();
if(!isset($_SESSION['userName'])){ //if login in session is not set
header("Location: login.php");
exit();
}
?>
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cad", $con)
or die('Could not select database');
$query="SELECT `town`, `location`, `incident_type`, `time_date`, `admin`, `id`
FROM `cad`
WHERE `id` =
$_GET[id]";
$result=mysql_query($query)
or die(mysql_error());
while( false!=($row=mysql_fetch_array($result)) )
{
echo '<h1>Town name: ', htmlspecialchars($row['town']), '</td>';
}
$town=$row['town'] ;
$location= $row['location'] ;
$incident_type=$row['incident_type'] ;
if(isset($_POST['save']))
{
$town = $_POST['town'];
$location = $_POST['location'];
$incident_type = $_POST['incident_type'];
mysql_query("UPDATE cad SET town ='{$town}', location ='{$location}',
incident_type ='{$incident_type}' WHERE `id` = $_GET[id]") or die(mysql_error());
echo "Saved! Redirecting back to the home page.";
}
mysql_close($con);
$id=$_GET['id'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit Incident</title>
</head>
<body>
<?php
echo "<h1>You are editing incident number # $id</h1>";
?>
<form method="post">
<table>
<tr>
<td>Town</td>
<td><input type="text" name="town" value="<?php echo $town; ?>"/></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="location" value="<?php echo $location; ?>"/></td>
</tr>
<tr>
<td>Incident Type</td>
<td><input type="text" name="incident_type" value="<?php echo $incident_type; ?>"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="save" value="Save" /></td>
</tr>
</table>
</body>
</html>
答案 0 :(得分:0)
你必须使用如下的查询
mysql_query("UPDATE cad SET town ='{$town}', location ='{$location}',
incident_type ='{$incident_type}' WHERE `id` = {$_GET['id']}") or die(mysql_error()); ;
答案 1 :(得分:0)
添加新的隐藏密钥以发布
<input type="hidden" name="savedid" value="<?php echo $_GET['id']?>" />
并在更新sql中
$town = $_POST['town'];
$location = $_POST['location'];
$incident_type = $_POST['incident_type'];
$savedid = $_POST['savedid'];
mysql_query("UPDATE cad SET town ='{$town}', location ='{$location}',
incident_type ='{$incident_type}' WHERE `id` = $savedid") or die(mysql_error());
echo "Saved! Redirecting back to the home page.";
如果安全性问题,您应该使用intval for theid
来过滤您的变量