【问题标题】:mysql database error : call to a member function query() on nullmysql 数据库错误:在 null 上调用成员函数 query()
【发布时间】:2019-07-06 10:23:04
【问题描述】:

我正在尝试使用 php 创建一个 mysql 表

我有以下函数来创建表

class dbActions{
public $connection;
function dbConnect(){
    $dbname = 'kilimokenya';
    $dbhost = 'localhost';
    $dbpass = '';
    $dbuser = 'root';

    $connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

    if($connection ->connect_errno) echo ($connection ->connect_error());
}

function createCustomerTbl(){
    GLOBAL $connection;
    $CustomerTbl = "CREATE TABLE customers_tbl(
        customer_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        firstname VARCHAR(30) NOT NULL,
        lastname VARCHAR(30) NOT NULL,
        emailAddress VARCHAR(30) NOT NULL,
        phone_number VARCHAR(15) NOT NULL,
        dateRegistered TIMESTAMP
        )";
    $check = $connection ->query($CustomerTbl);
    if(!$check)
        echo "Customer table not created because ".$connection ->error;
    return true;
}

我在这里调用函数:

$dbObject = new dbActions();
$dbObject ->dbconnect();

$dbObject ->createCustomerTbl();

运行代码时出现以下错误: 致命错误:在第 31 行的 C:\xampp\htdocs\current\kilimokenyafoods\common\server.php 中调用 null 上的成员函数 query()

我错过了什么?

【问题讨论】:

  • 要访问一个对象的成员,你必须使用$this->connection而不是$connection
  • @FranzGleichmann 你的意思是: $this ->connection ->query($customerTbl); ?
  • 仍然产生同样的错误
  • $connection 更改为私有,删除createCustomerTbl() 方法中的GLOBAL $connection;,并在任何地方使用$this->connection。还可以考虑切换到 PDO 和准备好的语句。
  • @krimaeu​​s 解决了它。谢谢

标签: php sql


【解决方案1】:

$connection 属性应该在类中使用$this 访问,而不是声明为全局变量。

上面可以重写一点,以遵循单例模式,以确保只有一个类的实例为您的脚本初始化

class dbAction{

    private static $instance=false;
    private $connection;

    private function __construct($dbhost, $dbuser, $dbpass, $dbname){
        $this->connection=new mysqli($dbhost, $dbuser, $dbpass, $dbname);
    }
    public static function initialise($dbhost, $dbuser, $dbpass, $dbname){
        if( !self::$instance ) self::$instance=new dbAction( $dbhost, $dbuser, $dbpass, $dbname );
        return self::$instance;
    }


    public function createCustomerTbl(){
        $sql='CREATE TABLE customers_tbl(
            customer_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            firstname VARCHAR(30) NOT NULL,
            lastname VARCHAR(30) NOT NULL,
            emailAddress VARCHAR(30) NOT NULL,
            phone_number VARCHAR(15) NOT NULL,
            dateRegistered TIMESTAMP)';
        $res = $this->connection->query( $sql );
        if( !$res )printf( 'Customer table not created because : %s', $this->connection->error );
        return $res;
    }
}



$dbo=dbAction::initialise( 'localhost', 'root', 'xxx', 'kilimokenya' );
$status=$dbo->createCustomerTbl();

echo $status ? 'good' : 'bad';

【讨论】:

  • 将其更改为使用准备好的语句,它会很完美。
  • 该查询不需要准备好的语句,但总的来说我同意应该使用它们
  • 你是对的。我完全跳过了查询的作用,我的反应开始了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多