猿问

未捕获的错误:在 [关闭] 中调用未定义的函数 bindValue()

我正在尝试从数据库中获取数据,但出现此错误


致命错误:未捕获错误:调用 C:\xampp\htdocs\includes\article.php:17 中未定义的函数 bindValue() 堆栈跟踪:#0 C:\xampp\htdocs\article.php(11):文章-> fetch_data('0') #1 {main} 在 C:\xampp\htdocs\includes\article.php 第 17 行抛出


C:\xampp\htdocs\includes\article.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\article.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();


}

?>


缥缈止盈
浏览 122回答 2
2回答

ibeautiful

bindValue()是 PDOStatement 对象的一个方法,由 prepare 调用返回。你想要这样的东西:$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 连接对象作为参数传递给 Article 对象。这称为依赖注入。class Article{&nbsp; &nbsp; protected $pdo;&nbsp; &nbsp; public function __construct($pdo) {&nbsp; &nbsp; &nbsp; &nbsp; $this->pdo = $pdo;&nbsp; &nbsp; }&nbsp; &nbsp; public function fetch_all() {&nbsp; &nbsp; &nbsp; &nbsp; $query = $this->pdo->prepare("SELECT * FROM articles");&nbsp; &nbsp; &nbsp; &nbsp; $query->execute();&nbsp; &nbsp; &nbsp; &nbsp; return $query->fetchAll();&nbsp; &nbsp; }}然后$pdo在实例化文章时作为参数传递:$article = new Article($pdo);
随时随地看视频慕课网APP
我要回答