首页 > 解决方案 > 为 foreach() 提供的参数无效 - 第 71 行

问题描述

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"; ?>

能够编辑数据库文件。

标签: phpmysql

解决方案


变量 $user 未定义。

放在$user = array();行前if (isset($_GET['id'])) {


推荐阅读