tab-6ren">
gpt4 book ai didi

php - OOP PDO 查询空

转载 作者:行者123 更新时间:2023-11-29 06:41:57 24 4
gpt4 key购买 nike

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


当我创建 var_dump 来使用时,一切顺利,但我不明白为什么我的查询为空

最佳答案

你正在运行

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

这是不正确的,并且会失败,因为查询具有可绑定(bind)参数,即 firstname = :firstname

你必须运行

Prepare
bindParam
execute

按照这个顺序

还有这个查询

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

当它运行时,会将该表中每一行中的firstname更改为$this->firstname中的内容

目前尚不清楚您是否实际在其中或 $conn 属性中设置了值。

关于php - OOP PDO 查询空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51177810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com