【发布时间】:2016-09-03 07:41:31
【问题描述】:
我正在尝试使用 PDO 将数据插入数据库。连接建立成功,但 prepare 功能不起作用。它给了我一个错误:
致命错误:在 null 上调用成员函数 query() E:\xammp\htdocs\OOP\Project\classes\insert.php 在第 8 行
我的 index.php 页面:
<?php
function __autoload($cl){
require_once "classes/$cl.php";
}
$connection = new database();
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$ph = $_POST['phone'];
try
{
$ins = new insert();
}
catch(PDOEXCEPTION $e)
{
echo $this->con_error . $e->getmessage();
}
}
类/数据库.php:
<?php
class database{
public $db;
public $con_error;
protected function connection(){
try
{
$this->db = new PDO("mysql:host=localhost;dbname=oop","root","");
}
catch(PDOException $e)
{
echo $this->con_error="An error in connection" . $e->getmessage();
}
}
public function __construct(){
return $this->connection();
}
}
类/插入.php:
<?php
class insert extends database{
public $stmt;
public function __construct(){
$stmt = $this->db->prepare("INSERT INTO `users` (`name`,`email`,`phone`) VALUES (:name,:email,:phone)");
$stmt->bindParam(":name",$name);
$stmt->bindParam(":email",$email);
$stmt->bindParam(":phone",$ph);
$stmt->execute();
}
}
【问题讨论】:
-
需要从子类的构造函数中调用父类的构造函数。它不会自动发生。
-
请使用
spl_autoload_register()