我正在尝试使用在这里创建的数据库类实例(类db)执行CRUD操作,但是我没有将数据库连接实例添加到另一个类中,而是在使用Netbeans IDE和MySql Database < / p>
<?php
class db
{
private $dsn="mysql:host=localhost;dbname=db_stud";
private $username="root";
private $password='';
protected $connection;
public function openConnection()
{
try
{
$this->connection=new PDO($this->dsn, $this->username, $this->password);
// set the PDO error mode to exception
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $this->connection;
} catch (PDOException $ex) {
print("Error ".$ex->getMessage()."<br/>");
die();
}
}
public function closeConnection()
{
$this->connection=null;
}
}
?>
以下是CRUD类
<?php
require_once("./db6.php");
class crud
{
public $id;#function to insert record into database
protected $dbcon;
public function insert($studentArr)
{
$sql="INSERT INTO 'student' ('fname','lname','gender','batch','address','mobile'"
. ",'age','dob','profilepic','fees') VALUES(:fname,:lname,:gender,:batch,:address"
. ":mobile,:age,:dob,:profile,:fees)";
$this->dbcon=new db;
$db= $this->dbcon->openConnection();
$result= $db->prepare($sql);
$pdoresult=$result->execute(array(":fname"=>$fname,":lname"=>$lname,":gender"=>$gender,":batch"=>$std,":address"=>$address,
":mobile"=>$mobile,":age"=>$age,":dob"=>$dob,":profile"=>$profile,":fees"=>$fees));
if($pdoresult)
{
$lastid=$db->lastInsertId();
$this->id=$lastid;
}
}
}