当我尝试使用wampServer在mysql中保存数据库时出现此错误。 mysqli_query()期望参数1为mysqli,中给出的对象
有3个PHP文件,db_config.php和db_connect.php以及create_person.php,我已经在phpmyadmin中使用了表PERSON。
db_config.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "othmane"); // database name
define('DB_SERVER', "localhost"); // db server
?>
&#13;
db_connect.php
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysqli_error());
// Selecing database
$db = mysqli_select_db($con, DB_DATABASE) or die(mysqli_error()) or die(mysqli_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysqli_close();
}
}
?>
&#13;
创建person.php:
<?php
/*
* Following code will create a new person row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['nom']) && isset($_POST['pass_world'])) {
$name = $_POST['nom'];
$pass = $_POST['pass_world'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result =mysqli_query($db,"INSERT INTO person (nom,pass_world) VALUES ('$name', '$pass')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
&#13;
答案 0 :(得分:3)
您
$db = new DB_CONNECT();
返回DB_CONNECT类的实例。
中需要什么
mysqli_query(...)
call是 mysqli_connect 调用返回的对象。 尝试更改您的:
function __construct() {
// connecting to database
$this->connect();
}
使用:
function __construct() {
// connecting to database
$this->conn = $this->connect();
}
然后,改变:
$result =mysqli_query($db,"INSERT INTO person (nom,pass_world) VALUES ('$name', '$pass')");
使用:
$result =mysqli_query($db->conn,"INSERT INTO person (nom,pass_world) VALUES ('$name', '$pass')");
另外,我认为您应该阅读PHP手册以了解您正在使用的功能: mysqli_connect mysqli_select_db