PDO插入值

时间:2014-12-12 16:11:28

标签: php mysql pdo

我已经遵循了一些教程,我无法理解为什么这不起作用。

我有一个类用户。它在__construct方法中获得数据库连接。接下来我有一个Create方法,需要通过在表中插入一些数据来创建用户,但它不会执行。我认为我的bindParam函数或MySQL插入代码有问题。 我有以下错误:

Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\www\samodel\object\users.php on line 44

如果你知道怎么回事,请帮我解决这个问题,谢谢你:

<?php
//Was Products, now Users
class Users{

  // database connection and table name
  private $conn;
  private $table_name = "users";

  // object properties
  public $id;
  public $username;
  public $first_name;
  public $last_name;
  public $email;
  public $password;

  public function __construct($db){
    $this->conn = $db;
  }

  // create user
  function create(){
    //write query
    $query = "INSERT INTO
             " . $this->table_name . "
                SET
                  username = ?, first_name = ?, last_name = ?";

    $stmt = $this->conn->prepare($query);

    $stmt->bindParam("username", $this->username);
    $stmt->bindParam("first_name", $this->first_name);
    $stmt->bindParam("last_name", $this->last_name);

    if($stmt->execute()){
      return true;
    }else{
      return false;
    }
  }
}
?>

2 个答案:

答案 0 :(得分:3)

你在这里混合了两种技术 - 你正在准备带有位置占位符的语句,但是根据名称进行绑定 - 你应该选择一个并坚持下去。

使用位置占位符:

$query = "INSERT INTO
            " . $this->table_name . "
        SET
            username = ?, first_name = ?, last_name = ?";

$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->username);
$stmt->bindParam(2, $this->first_name);
$stmt->bindParam(3, $this->last_name);

使用命名占位符:

$query = "INSERT INTO
            " . $this->table_name . "
        SET
            username = :username, first_name = :first_name, last_name = :last_name";

$stmt->bindParam("username", $this->username);
$stmt->bindParam("first_name", $this->first_name);
$stmt->bindParam("last_name", $this->last_name);

答案 1 :(得分:0)

我认为你的sql很糟糕 尝试

$query = "INSERT INTO {$this->table_name} (username, first_name, last_name) VALUES (:username, :first_name, :last_name)";