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/

相关文章:

php - 如何防止 PHP 中的 SQL 注入(inject)?

如果文本太长,Mysql 数据库不会保存文本

php - laravel 5.8 Eloquent : has many relations model

java - 我的方法太具体了。我怎样才能使它更通用?

php - 通过 AJAX 将变量从 JavaScript 传递到 PHP

php - 如何在 WordPress 中添加 SSL 和 HTTPS

java - 用于添加功能的继承

php - 在 PHP5 中创建单例设计模式

php - 截断字段 Php 的输出

mysql - 用于搜索城市、州和国家/地区(如 expedia.co.in)的 SQL 查询