Nevada
Nevada

Reputation: 277

PDO Insert value

I have followed some tutorial and I can't understand why this doesn't work.

I have a class Users. It gets a DB connection in the __construct method. Next I have a Create method, that needs to create a user by inserting some data in the table, but it does not execute. I think I have problem with the bindParam function or with MySQL insert code. I have following error:

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

Please help me to solve this problem if you know how, Thank you:

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

Upvotes: 1

Views: 301

Answers (2)

jsHate
jsHate

Reputation: 599

I think you have bad sql try

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

Upvotes: 0

Mureinik
Mureinik

Reputation: 311228

You are mixing two techniques here - you are preparing the statement with positional placeholders, but binding according to names - you should pick one and stick to it.

With positional placeholders:

$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);

With named placeholders:

$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);

Upvotes: 3

Related Questions