简体   繁体   中英

Not able to insert values into Database using oop concept in php

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();
?>

Even after passing the $conn variable in mysqli_query , I'm not able to insert values in the database. Cannot able to figure out, what's happening.

You should have to prepare your SQL query with quotes as below

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

Also you should use your private class member $conn as $this->conn .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM