我今天编写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>
答案 0 :(得分:0)
默认情况下,PHP不会调用祖先构造函数,因此当您实例化sql
对象时,$this->dbconnection
不会存在,因为Databaseconnection::__construct
永远不会被调用。< / p>
您的代码应为
class sql extends databasdeconnection {
function __construct() {
parent::__construct(); // create dbconnection
... use $this->dbconnection
}
}