我正在尝试从数据库中获取数据,但是我得到了此错误
致命错误:未定义的错误:c: xampp xampp htdocs incress incress article.php中的未定义函数bindvalue((:17堆栈跟踪:#0 c: xampp xampp htdocs htdocs article.php(11(:Artist-> fetch_data('0'(#1 {main}扔在C: Xampp htdocs incruph incruph actift.prat.php in 17
上
c: xampp htdocs include acrats.php
<?php
class Article {
public function fetch_all(){
global $pdo;
$query = $pdo->prepare("SELECT * FROM articles");
$query->execute();
return $query->fetchAll();
}
public function fetch_data($article_id){
global $pdo;
$query = $pdo->prepare("SELECT * FROM articles WHERE article_id = ? ");
$query = bindValue(1, $article_id);
$query->execute();
return $query->fetch();
}
}
?>
c: xampp htdocs actity.php
<?php
include_once('includes/connection.php');
include_once('includes/article.php');
$article = new Article;
if (isset($_GET['id'])){
$id = $_GET['id'];
$data = $article->fetch_data($id);
print_r($data);
} else {
header('Location: index.php');
exit();
}
?>
更改以下内容:
$query = bindValue(1, $article_id);
到这个
$query->bindValue(1, $article_id);
bindValue
是一种pdostatement的方法,而不是单独的功能https://www.php.net/manual/en/pdostatement.bindvalue.php
bindValue()
是pdostatement对象的一种方法,该对象由准备呼叫返回。您想要这样的东西:
$query = $pdo->prepare('SELECT * FROM articles WHERE article_id = ?');
$query->bindValue(1, $article_id);
$query->execute();
您也可以使用名为参数:
$query = $pdo->prepare('SELECT * FROM articles WHERE article_id = :article_id');
$query->bindValue('article_id', $article_id);
$query->execute();
另外,不要依靠全局变量,它会打破面向对象的编程的基本概念。而是将PDO连接对象作为参数传递到文章对象中。这称为依赖注入。
class Article
{
protected $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
}
public function fetch_all() {
$query = $this->pdo->prepare("SELECT * FROM articles");
$query->execute();
return $query->fetchAll();
}
}
然后,当您实例化文章时,只需通过$pdo
作为参数:
$article = new Article($pdo);