dongzenglin8292
2015-11-12 10:02
浏览 163
已采纳

调用未定义的方法DB_CONNECT :: query()

I have a problem with my php code, i've read a lot of answer but i didn't find the answer for me. I have two files: db_connect.php

<?php

/**
* A class file to connect to database
*/
class DB_CONNECT {

// constructor
function __construct() {
    // connecting to database
    $this->connect();
}

// destructor
function __destruct() {
    // closing db connection
    $this->close();
}

/**
 * Function to connect with database
 */
function connect() {
    // import database connection variables
    require_once __DIR__ . '/config.php';

    // Connecting to mysql database
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);


    // Selecing database
    $mysqli ->select_db(DB_DATABASE);

    // returing connection cursor
    return $mysqli; 
}



/**
 * Function to close db connection
 */
function close() {
    // closing db connection
    mysql_close();
$mysqli->close();
}

}

?>

and get_courses_details.php

<?php

/*
 * Following code will list all the products
 */



// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
$result = $db -> query("SELECT * FROM corsi");

// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["corsi"] = array();

while ($row = mysql_fetch_array($result)) {
    // temp user array
    $corsi = array();
    $corsi ["corso_id"] = $row["corso_id"];
    $corsi ["corso_nome"] = $row["corso_nome"];


    // push single product into final response array
    array_push($response["corsi"], $corsi);
}
// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No courses found";

// echo no users JSON
echo json_encode($response);
}
?>

but when i try to run it display me this message: Fatal error: Call to undefined method DB_CONNECT::query() in get_courses_details.php on line 19

Do you know how I can do to fix it?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzhuo1930 2015-11-12 10:09
    已采纳

    You're making a new class object using $db = new DB_CONNECT();. Then after you're trying to run $result = $db -> query("SELECT * FROM corsi");, but returns a syntax error, since there is no method query() in your class object.

    What you want to do is make a public property and define this in your connect() method, for example:

    class DB_CONNECT {
        public $sth;
    
        ...
    
        public function connect() {
            ...
    
            $this->sth = $mysqli;
        }
    }
    

    Now you can use $db->sth->query(), as $db->sth is your MySQL object now.

    点赞 打赏 评论

相关推荐 更多相似问题