AkashiSh
AkashiSh

Reputation: 1

OOP PDO Query null

<?php
class User {
  private $conn;
  private $table_name = "users";

  public $id;
  public $firstname;

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

   public function create(){
     $query = "INSERT INTO
              " . $this->table_name . "
              SET
              firstname = :firstname";

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

        $this->firstname=htmlspecialchars(strip_tags($this->firstname));

        $stmt->bindParam(':firstname', $this->firstname);

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

Uncaught Error: Call to a member function query() on null

Why my query is NULL?


When I make a var_dump to use everything goes well but I do not understand why my query is null

Upvotes: 0

Views: 49

Answers (1)

RiggsFolly
RiggsFolly

Reputation: 94682

You are running

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

That is incorrect and will fail as the query has a bindable parameter i.e. firstname = :firstname

You have to run

Prepare
bindParam
execute

In that order

Also this query

$query = "INSERT INTO" . $this->table_name . "
            SET firstname = :firstname";

When it does run, will changefirstname in every row in that table to whatever is in $this->firstname

And it is not clear that you have actually set a value in there OR in the $conn property.

Upvotes: 2

Related Questions