我正在使用以下代码更新记录。不好的是,它没有更新记录,但它正在添加新记录。
我做错了什么?我希望它更新记录而不是创建现在的记录。
我的修改网址如下所示:http://randomsite.com/modify.php?id=1
Modify.php代码:
<?php
require_once("connect.php");
$query = "SELECT * FROM cars WHERE id = :id";
$result = $odb->prepare($query);
$result->execute(array(':id' => $_REQUEST['id']) );
while ($row = $result->fetch(PDO::FETCH_ASSOC)) { ?>
<h1>Modify a car</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Brand: <input type="text" name="brand" value="<?php echo $row['brand']; ?>" /><br />
Model: <input type="text" name="model" value="<?php echo $row['model']; ?>" /><br />
Year: <input type="text" name="year" value="<?php echo $row['year']; ?>" /><br />
ID: <input type="text" name="id" value="<?php echo $row['id']; }?>" /><br />
<input type="submit" value="Modify" />
</form>
<?php
if(isset($_POST['submit'])) {
$id = $_POST['id'];
$brand = $_POST['brand'];
$model = $_POST['model'];
$year = $_POST['year'];
$q = "UPDATE cars WHERE id = $_GET[id] (id, brand, model, year) VALUES(:id, :brand, :model, :year)";
$query = $odb->prepare($q);
$results = $query->execute(array(
":id" => $id,
":brand" => $brand,
":model" => $model,
":year" => $year,
));
}
?>
答案 0 :(得分:4)
你的SQL应该看起来像这样:
$q = "UPDATE cars SET
id = :id,
brand = :brand,
model = :model,
year = :year
WHERE id = :oldid";
$query = $odb->prepare($q);
$results = $query->execute(array(
":id" => $id,
":brand" => $brand,
":model" => $model,
":year" => $year,
":oldid" => $_GET['id'],
));
作为旁注,尽量不要在SQL中添加变量(比如$ _GET ['id']),使用PDO的一部分原则是避免这样做。
答案 1 :(得分:1)
搞定了!
工作代码:
<?php
require_once("connect.php");
$query = "SELECT * FROM cars WHERE id = :id";
$result = $dbh->prepare($query);
$result->execute(array(':id' => $_REQUEST['id']) );
while ($row = $result->fetch(PDO::FETCH_ASSOC)) { ?>
<h1>Modify a car</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Brand: <input type="text" name="brand" value="<?php echo $row['brand']; ?>" /><br />
Model: <input type="text" name="model" value="<?php echo $row['model']; ?>" /><br />
Year: <input type="text" name="year" value="<?php echo $row['year']; ?>" /><br />
ID: <input type="text" name="id" value="<?php echo $row['id']; }?>" /><br />
<input type="submit" value="Modify" name="submit"/>
</form>
<?php
if(isset($_POST['submit'])) {
$brand = $_POST['brand'];
$model = $_POST['model'];
$year = $_POST['year'];
$id = $_POST['id'];
$queryupdate = "UPDATE cars SET
brand= :brand, model= :model, year= :year WHERE id= :id";
$q = $dbh->prepare($queryupdate);
$q->execute(array(
":id" => $id,
":brand" => $brand,
":model" => $model,
":year" => $year));
//Send them back to the page they were at/
header("location:admin.php");
}
?>