PDO Mysql,想要更新甚至INSERT数据

时间:2017-07-10 01:54:21

标签: php mysql pdo crud

我在这里有一些问题,我想在CRUD中更新数据,数据甚至添加新的(如插入)。

有任何想法可以解决吗?感谢。

有我的代码,

    if ($valid) {
      $pdo = Database::connect();
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $sql = "UPDATE customers
              SET name = ?, email = ?, address = ?
              WHERE id = ?";
      $q = $pdo->prepare($sql);
      $q->execute(array($name,$email,$address));
      Database::disconnect();
      header("Location: index.php");
    }
  }else {
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "SELECT * FROM customers WHERE id = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    $name = $data['name'];
    $email = $data['email'];
    $address = $data['address'];
    Database::disconnect();
  }

2 个答案:

答案 0 :(得分:2)

在预准备语句中绑定id

    if ($valid) {
      $pdo = Database::connect();
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $values = array($name,$email,$address);
      if($id) {
          $sql = "UPDATE customers
                  SET name = ?, email = ?, address = ?
                  WHERE id = ?";
          $values[] = $id;
       } else {
          $sql = "INSERT INTO customers (name, email, address)
                  VALUES (?,?,?)";
       }
       $q = $pdo->prepare($sql);
       $q->execute($values);
      Database::disconnect();
      header("Location: index.php");
    }
  }else {
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "SELECT * FROM customers WHERE id = ?";
    $q = $pdo->prepare($sql);
    $q->execute(array($id));
    $data = $q->fetch(PDO::FETCH_ASSOC);
    $name = $data['name'];
    $email = $data['email'];
    $address = $data['address'];
    Database::disconnect();
  }

见第8行(遗漏**)

修改 为case $ id添加了一个插入查询为空 基于对评论的理解

答案 1 :(得分:0)

绑定变量的数量与令牌数量不匹配

$sql = "UPDATE customers
      SET name = ?, email = ?, address = ?
      WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$email,$address));

你有四个令牌?应该有四个参数,如下:

$q->execute(array($name,$email,$address,$id));

并注意不要将header("Location: index.php");放在与index.php相同的文件中,因为这会循环,您将收到如下错误:

  

您的网站管理员重定向了您太多次