简体   繁体   中英

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM