duanmianhong4893 2016-07-21 21:54
浏览 62
已采纳

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

i code php script today and got fatal error message, i cant find any solution in internet, please help me!

Fatal error: Call to a member function query() on null in oop.php on line 23

<?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;
        }
    }

}

End there is 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>
  • 写回答

1条回答 默认 最新

  • drpzr64329 2016-07-21 21:58
    关注

    PHP doesn't call ancestral constructors by default, so when you instantiate an sql object, $this->dbconnection won't exist, because Databaseconnection::__construct never got called.

    Your code should be

    class sql extends databasdeconnection {
       function __construct() {
           parent::__construct(); // create dbconnection
           ... use $this->dbconnection
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在线手电筒追加按钮JS
  • ¥15 调用函数时,无关变量的改变引起函数值的改变
  • ¥15 xy坐标转化为经纬度坐标
  • ¥15 一般三角模糊数的上界值和下届值取中值的多少比较合理?
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥20 Hbase启动失败,无法启动HMaster
  • ¥20 Lumerical FDTD solutions 中模型的相对阻抗,有效介电常数和有效磁导率的实部和虚部的数据如何获得?
  • ¥100 sql reporting service 远程smtp服务器配置支持
  • ¥15 ppyoloe_r带角度目标检测,loss_cls没法收敛
  • ¥15 淘宝交易指数如何解读,其关联的数据指标是什么