gpt4 book ai didi

php - OOP PHP 查询 mysql 时出错

转载 作者:行者123 更新时间:2023-11-29 08:15:54 24 4
gpt4 key购买 nike

我刚刚开始使用 OOP,在使用教程时遇到了以下错误:

Warning: Missing argument 2 for MySQLDatabase::query(), called in
/Applications/MAMP/htdocs/object-oriented/public/index.php on line 7 and defined in
/Applications/MAMP/htdocs/object-oriented/includes/database.php on line 28

Notice: Undefined variable: sql in
/Applications/MAMP/htdocs/object-oriented/includes/database.php on line 29

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in
/Applications/MAMP/htdocs/object-oriented/includes/database.php on line 29

这是我的数据库.php

<?php

require('config.php');

class MySQLDatabase {

public $connection;

public function open_connection() {
$this->$connection = mysqli_connect('DB_SERVER', 'DB_USER', 'DB_PASS');
if (!$this->connection) {
die("Database connection failed");
} else {
$db_select = mysqli_select_db($this->connection, DB_NAME);
if (!$select_db) {
die("Database selection failed");
}
}
}

public function close_connection() {
if (isset($this->connection)) {
mysqli_close($this->connection);
unset($this->connection);
}
}

public function query($connection, $sql) {
$result = mysqli_query($this->connection, $sql);
$this->confirm_query($result);
return $result;
}

以及我试图在其中测试 query() 方法的 index.php。

$sql = "INSERT INTO users (id, username, password, first_name, last_name) ";
$sql .= "VALUES (1, 'andrei', 'password', 'Andrei', 'Popa')";
$result = $database->query($sql);

$sql = "SELECT * FROM users WHERE id = 1";
$result_set = $database->query($sql);
$found_user = mysqli_fetch_array($result_set);
echo "Found user!" . $found_user['username'];

知道我做错了什么吗?谢谢

最佳答案

public function query($connection, $sql) {

您不需要第一个参数,因为连接是您的类的属性。因此,只需将 $sql 传递到查询方法中,就像使用该方法时所做的那样:

public function query($sql) {

关于php - OOP PHP 查询 mysql 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20619468/

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