简体   繁体   English

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

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

dbclass.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 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. 即使在mysqli_query传递了$conn变量后,我也无法在数据库中插入值。 Cannot able to figure out, what's happening. 无法确定发生了什么事。

You should have to prepare your SQL query with quotes as below 您必须准备带引号的SQL查询,如下所示

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

Also you should use your private class member $conn as $this->conn . 另外,您应该将私有类成员$conn用作$this->conn

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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