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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?