gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:46:21 25 4
gpt4 key购买 nike

我正在尝试将数据插入 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com