【问题标题】:Fatal error: Call to a member function query() on null in oop.php致命错误:在 oop.php 中调用 null 上的成员函数 query()
【发布时间】:2016-07-21 21:54:55
【问题描述】:

我今天编写 php 脚本并收到致命错误消息,我在互联网上找不到任何解决方案,请帮助我!

致命错误:在第 23 行的 oop.php 中,在 null 上调用成员函数 query()

<?php

class DatabaseConnection {

    public $dbconnection;
    public $dbhost;
    public $dbuser;
    public $dbpass;
    public $dbname;

// Create connection
    public function __construct($dbhost, $dbuser, $dbpass, $dbname) {
    $this->dbconnection = new mysqli($this->dbhost = $dbhost, $this->dbuser = $dbuser, $this->dbpass = $dbpass, $this->dbname = $dbname);
    }

}

class sql extends DatabaseConnection {

    public $sql;

    public function __construct($sql) {
        if ($this->dbconnection->query($this->sql=$sql) === TRUE) {
        echo "New record created successfully";
        } else {
        echo "Error: " . $this->sql . "<br>" . $this->dbconnection->error;
        }
    }

}

最后是index.php

<?php
require 'oop.php';
$mydb = new DatabaseConnection("localhost", "admin", "admin", "tutorial");

if(isset($_POST['submit'])) {

$firstname = $_POST['firstname'];
$username = $_POST['username'];
$password = $_POST['password'];

$insertdata = new sql("INSERT INTO tutorial (firstname, username, password)
VALUES ('$firstname', '$username', '$password')");
?>

<p>Firstname: <?php echo $firstname; ?></p>
<p>Username: <?php echo $username; ?></p>
<p>Password: <?php echo $password; ?></p>

<?php } ?>



<form method="post">
<input type="text" name="firstname" placeholder="Firstname"/></br>
<div style="height:10px;"></div>
<input type="text" name="username" placeholder="Username"/></br>
<div style="height:10px;"></div>
<input type="password" name="password" placeholder="Password"/></br>
<div style="height:10px;"></div>
<input type="submit" name="submit" value="Enter"/>

</form>

【问题讨论】:

    标签: php database oop insert


    【解决方案1】:

    默认情况下,PHP 不调用祖先构造函数,因此当您实例化 sql 对象时,$this-&gt;dbconnection 将不存在,因为从未调用过 Databaseconnection::__construct

    你的代码应该是

    class sql extends databasdeconnection {
       function __construct() {
           parent::__construct(); // create dbconnection
           ... use $this->dbconnection
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 2020-03-11
      相关资源
      最近更新 更多