PHP OOP query() 错误 - 调用未定义的方法 connection::query()

标签 php mysql oop

我正在尝试将数据插入 mysql 数据库。 我有类(class)联系

    class connection{
function __construct(){
    $servername = 'localhost';
    $username = 'root';
    $password = '';
    $database='products2';

    // Create connection
    $conn = new mysqli($servername, $username, $password,$database);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
        return false;
    }else{
        echo "succesful connection!</br>";
        $this->query=$conn;
        return true;
    }       
}
}

女巫中的另一个类我尝试将数据插入数据库(我尝试在该类的 __construct 中执行此操作)

$sql="INSERT INTO products (name,price,category,f_material,f_size) VALUES ('nosaukums','cena','kategorija,'materials','izmers')";
$db=new connection();
$result=$db->query($sql);

但是我得到这个错误:

Fatal error: Call to undefined method connection::query() in ....

最佳答案

为了使用查询(来自 mysqli 类)方法,您需要创建一个新方法 public function query() {}。这个方法就可以使用mysqli方法了。最后,您将能够获得相同的结果,但是通过在您自己的对象 ($db) 上应用“查询”,就像这样 $result = $db->query($sql);

这是类(class):

<?php

class connection{

  // define a variable for the database connection
  private $conn;

  // when an instance of 'connection' class is created a connection is made through mysqli
  public function __construct()
  {
    $servername = 'localhost';
    $username = 'root';
    $password = '';
    $database='products2';

    // the connection is stored inside the private variable
    $this->conn = new mysqli($servername, $username, $password,$database);

    // Check connection
    if ($this->conn->connect_error) {
        die("Connection failed: " . $this->conn->connect_error);
        return false;
    } else{
        echo "succesful connection!</br>";
        return true;
    }       
  }

  // method used to send a query to database
  public function query($sql)
  {
    // here you use the connection made on __construct() and apply the method query. Basically we are using inside our method (called query) a method (call query too) from the mysqli class
    $this->conn->query($sql);
    return true;
  }

}

调用方法:

<?php

    // prepare the SQL request
    $sql = "INSERT INTO products (name,price,category,f_material,f_size) VALUES ('nosaukums','cena','kategorija,'materials','izmers')";

    // create a new instance of the class connection
    $db = new connection();

    // run the method $sql on the newly created instance $db
    $result = $db->query($sql);

关于PHP OOP query() 错误 - 调用未定义的方法 connection::query(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38463737/

相关文章:

oop - 在使用 jQuery getJSON 调用的对象上运行初始化方法

Python 无法识别属性

java - do while 循环错误

php - WooCommerce:强制执行最小长度电话号码字段

php - 将 mysql DB 时间戳转换为 PHP touch 的 int 时间

php - 我可以在 PHP 中混合使用 MySQL API 吗?

LIKE 查询中的 MySQL 列值

php - 覆盖特征方法时检测递归

php - 无法从 GCM 获取消息

MySQL 选择两列上的唯一记录