在null上调用成员函数query()

时间:2016-02-17 16:32:56

标签: php

我是PHP新手编程的新手,我正在创建一个接收查询的PHP类,但是当召唤给我错误时#34; PHP致命错误:调用null上的成员函数query()&#34 ;。你能帮我看看发生了什么吗?

这是PHP类代码

class conectar{

    public $conexion;   
    var $svrName;
    var $user;
    var $pwd;
    var $dbName;
    var $consult;


    function set_conexion($new_conexion){
        $this->conexion=$new_conexion;
    }
    function get_conexion(){
        return $this->conexion;
    }

    function set_server($new_svrName){
        $this->svrName=$new_svrName;
    }
    function get_server(){
        return $this->svrName;
    }

    function set_user($new_usere){
        $this->user=$new_user;
    }
    function get_user(){
        return $this->user;
    }

    function set_pwd($new_pwd){
        $this->pwd=$new_pwd;
    }
    function get_pwd(){
        return $this->pwd;
    }

    function set_dbName($new_dbName){
        $this->pwd=$new_dbName;
    }
    function get_dbName(){
        return $this->dbName;
    }

    function conectarDB($svrName, $user, $pwd,$dbName){
        $conexion = mysqli_connect($svrName, $user, $pwd,$dbName); 
        return $conexion;
    }

    function consultaDB($consult){
        $result = $conexion->query($conexion,$consult);
        return $result;     
    }

    function disconnectDB($conexion){
        $close = mysqli_close($conexion); 
        return $close;
    }
}

所以我打电话给

<?php
include("conectar.php");

$con = new conectar();
$con->conectarDB("localhost","root","root","contactos");

$query = "Select * from pais order by nombre";

$ejeConsulta = $con->consultaDB($query);

while ($result = $ejeConsulta->fetch_assoc()){
    echo "<option value='".$result["pais"]."'>".$result["pais"]."</`enter code here`option>";
}
?>

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您的变量范围错误。试试这个:

function conectarDB($svrName, $user, $pwd,$dbName){
    $this->conexion = mysqli_connect($svrName, $user, $pwd,$dbName); 
    return $this->conexion;
}

function consultaDB($consult){
    $result = $this->conexion->query($consult);
    return $result;     
}