无法使用php中的oop概念将值插入数据库

时间:2016-12-03 10:34:45

标签: php database login insert

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变量后,我也无法在数据库中插入值。 无法弄清楚,发生了什么。

1 个答案:

答案 0 :(得分:1)

您必须使用以下引号准备SQL查询

$q1 = "INSERT INTO sbook (title,price) VALUES ('$this->title','$this->price')";

此外,您应该将您的私人班级成员$conn用作$this->conn

$this->conn = DB::connect();