我正在尝试为我的聊天应用程序处理我的ajax.php但由于某种原因我无法连接到我的数据库。我不明白为什么我收到此错误消息
注意:未定义的变量:第21行的dbOptions
捕获致命错误:传递给DB :: init()的参数1必须是数组类型,给定null,在第21行调用并在第20行定义
这是我的代码
ajax.php
<?php
require "classes/DB.class.php";
require "classes/Chat.class.php";
require "classes/ChatBase.class.php";
require "classes/ChatLine.class.php";
require "classes/ChatUser.class.php";
session_name('webchat');
session_start();
if(get_magic_quotes_gpc()){
// If magic quotes is enabled, strip the extra slashes
array_walk_recursive($_GET,create_function('&$v,$k','$v = stripslashes($v);'));
array_walk_recursive($_POST,create_function('&$v,$k','$v = stripslashes($v);'));
}
try{
// Connecting to the database
DB::init($dbOptions);
$response = array();
// Handling the supported actions:
switch($_GET['action']){
case 'login':
$response = Chat::login($_POST['name'],$_POST['email']);
break;
case 'checkLogged':
$response = Chat::checkLogged();
break;
case 'logout':
$response = Chat::logout();
break;
case 'submitChat':
$response = Chat::submitChat($_POST['chatText']);
break;
case 'getUsers':
$response = Chat::getUsers();
break;
case 'getChats':
$response = Chat::getChats($_GET['lastID']);
break;
default:
throw new Exception('Wrong action');
}
echo json_encode($response);
}
catch(Exception $e){
die(json_encode(array('error' => $e->getMessage())));
}
?>
DB.class.php
<?php
class DB {
private static $instance;
private $MySQLi;
private function __construct(array $dbOptions){
$this->MySQLi = @ new mysqli( $dbOptions['localhost'],
$dbOptions['root'],
$dbOptions[''],
$dbOptions['webchat'] );
if (mysqli_connect_errno()) {
throw new Exception('Database error.');
}
$this->MySQLi->set_charset("utf8");
}
public static function init(array $dbOptions){
if(self::$instance instanceof self){
return false;
}
self::$instance = new self($dbOptions);
}
public static function getMySQLiObject(){
return self::$instance->MySQLi;
}
public static function query($q){
return self::$instance->MySQLi->query($q);
}
public static function esc($str){
return self::$instance->MySQLi->real_escape_string(htmlspecialchars($str));
}
}
?>
我做错了吗?
答案 0 :(得分:0)
$dbOptions
有值。加入ajax.php
$dbOptions = array();
$dbOptions['host'] = "localhost";
$dbOptions['user'] = "root";
$dbOptions['pass'] = "";
$dbOptions['database'] = "webchat";
// Connecting to the database
DB::init($dbOptions);
然后修改DB.class.php
private function __construct(array $dbOptions){
$this->MySQLi = new mysqli($dbOptions['host'],
$dbOptions['user'],
$dbOptions['pass'],
$dbOptions['database'] );
if (mysqli_connect_errno()) {
throw new Exception('Database error.');
}
$this->MySQLi->set_charset("utf8");
}
此外,永远不要在连接数据库时抑制错误。在异常逻辑中处理它们,如果失败则发回HTTP STATUS 500
。