简体   繁体   English

OOP PDO查询为空

[英]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 未捕获的错误:在null上调用成员函数query()

Why my query is NULL? 为什么我的查询为NULL?


When I make a var_dump to use everything goes well but I do not understand why my query is null 当我使var_dump使用一切顺利时,但我不明白为什么查询为空

You are running 你在跑步

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

That is incorrect and will fail as the query has a bindable parameter ie firstname = :firstname 这是不正确的,并且将失败,因为查询具有可绑定的参数,即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 change firstname in every row in that table to whatever is in $this->firstname 当它运行,将改变firstname在该表中的每一行中无论是在$this->firstname

And it is not clear that you have actually set a value in there OR in the $conn property. 还不清楚您是否实际上在那里或$conn属性中设置了一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM