dbclass.php
<?php
class DB{
public static function connect(){
$conn = mysqli_connect("localhost","root","yash","sample");
return $conn;
}
}
$dbb = new DB;
$dbb->connect();
?>
classone.php
<?php
include('dbclass.php');
class Books {
private $title;
private $price;
private $conn;
function __construct($title,$price){
$this->title = $title;
$this->price = $price;
}
function getDetails(){
echo $this->title."</br>";
echo $this->price;
}
public function insertbook(){
$conn = DB::connect();
$q1 = "INSERT INTO sbook (title,price) VALUES ($this->title,$this->price)";
$run = mysqli_query($conn,$q1);
}
}
$physics = new Books("physics",20);
$physics->getDetails();
$physics->insertbook();
?>
即使在$conn
中传递mysqli_query
变量后,我也无法在数据库中插入值。
无法弄清楚,发生了什么。
答案 0 :(得分:1)
您必须使用以下引号准备SQL查询
$q1 = "INSERT INTO sbook (title,price) VALUES ('$this->title','$this->price')";
此外,您应该将您的私人班级成员$conn
用作$this->conn
。
$this->conn = DB::connect();