6月8日**
我已经更新了代码,现在它更新了数据库,如果我输入的数据相同,则会在重复错误下面触发错误,是否有可能只是说出它是重复的而不是告诉我有个大错误吗?
UPDATE clients2 SET id = :id, fullname = :fullname, paypal = :paypal, email = :email, serial_no = :serial_no, toolkitserial = :toolkitserial WHERE id = :id
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '11111-11111-11111-11111' for key 'serial'
因此代码几乎完整,剩下的唯一一件事就是修复复制错误。
<?php
/**
* Use an HTML form to edit an entry in the
* users table.
*
*/
require "../config.php";
require "../common.php";
if (isset($_POST['submit'])) {
if (!hash_equals($_SESSION['csrf'], $_POST['csrf'])) die();
try {
$connection = new PDO($dsn, $username, $password, $options);
$user =[
"id" => $_POST['id'],
"fullname" => $_POST['fullname'],
"paypal" => $_POST['paypal'],
"email" => $_POST['email'],
"serial_no" => $_POST['serial_no'],
"toolkitserial" => $_POST['toolkitserial'],
];
$sql = "UPDATE clients2
SET id = :id,
fullname = :fullname,
paypal = :paypal,
email = :email,
serial_no = :serial_no,
toolkitserial = :toolkitserial
WHERE id = :id";
$statement = $connection->prepare($sql);
$statement->execute($user);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
$user = array();
if (isset($_GET['id'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$id = $_GET['id'];
$sql = "SELECT * FROM clients2 WHERE id = :id";
$statement = $connection->prepare($sql);
$statement->bindValue(':id', $id);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
} else {
echo "Something went wrong!";
exit;
}
?>
<?php require "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['fullname']); ?> successfully updated.</blockquote>
<?php endif; ?>
<h2>Edit a user</h2>
<form method="post">
<input name="csrf" type="hidden" value="<?php echo escape($_SESSION['csrf']); ?>">
<?php foreach ($user as $key => $value) : ?>
<label for="<?php echo $key; ?>"><?php echo ucfirst($key); ?></label>
<input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'id' ? 'readonly' : null); ?>>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit">
</form>
<a href="index.php">Back to home</a>
<?php require "templates/footer.php"; ?>
能够编辑数据库文件。
答案 0 :(得分:1)
应该像
$sql = "UPDATE clients2
SET fullname = :fullname,
paypal = :paypal,
email = :email,
serial_no = :serial_no
WHERE client_id = :id";
您正在使用id
,但已将其更改为client_id
答案 1 :(得分:1)
未定义变量$ user。
将$user = array();
放在if (isset($_GET['id'])) {
行之前
答案 2 :(得分:0)
如果要更新,则需要知道'id'
。
if(!isset($_GET['id'])) { // not set redirect to ....
$id = $_GET['id']; // if isset
然后更新。
此代码看起来不太好:
如果使用OO,请使用databaseobject.class.php
之类的东西,然后插入,更新,删除,按ID查找,按SQL查找.....
使用它,例如static public function find_by_id($id)
。