dongxiai3003 2016-09-26 23:21
浏览 25
已采纳

我的PDO课程在哪里出错了? [关闭]

I am a little new to the PDO object, and I am simply trying to make a connection to the database and return a mySQL query. I have scoured the internet (including this site) to try and find the solution. I have found many similar solutions, but nothing is working. I know that it is probably a really simple fix, but I can't seem to find it.

Thanks in advance for your help!

PDO Class

 <?php
    class Database {

    private static $host = "localhost";
    private static $db_name = "c9";
    private static $username = "theandrewilliam";
    private static $password = "";
    private static $socket = "mysql";

    //Instance of class
    private $instance = NULL;

    //Connection to Database (predefined function)
    public function __construct(){

        if($this -> instance == NULL){
            try{

                $db = new PDO(self::$socket.':'.'host'.'='.self::$host.';'
                .'dbname'.'='.self::$db_name,self::$username,self::$password);

                $this -> instance = $db;

            } catch(PDOException $e){

                die($e -> getMessage());

            }
        }

    }

    //Queries
    public function query($sql){

        $query = $this -> instance = prepare($sql);
        $query -> execute();

        return $query;

    }

    }

PDO Object


<?php
    require_once('db.php');

    $data = new Database();

    $sq = 'SELECT * FROM body';

    $result = $data -> query($sq);

    while($row = $result -> $query -> fetch(PDO::FETCH_ASSOC)){

    $body = $row['text'];
    echo $body;

    }

Error thrown

Fatal error: Call to undefined function prepare() in /home/ubuntu/workspace/db.php on line 36 Call Stack: 0.0003 233728 1. {main}() /home/ubuntu/workspace/post.php:0 0.0011 254688 2. Database->query() /home/ubuntu/workspace/post.php:8

  • 写回答

3条回答 默认 最新

  • dongwenyou4298 2016-09-26 23:33
    关注

    The method fetch() is used by a PDOStatement (here, $result). So you should remove $query in your while.

    while($row = $result -> fetch(PDO::FETCH_ASSOC)){
    
        $body = $row['id'];
        echo $body;
    
    }
    

    https://secure.php.net/manual/en/pdostatement.fetch.php

    Edit: You have some typo when using the prepare method, it should be:

    $query = $this -> instance -> prepare($sql);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失