0
我正在尝试为我的聊天应用程序处理我的ajax.php,但由于某种原因我无法连接到我的数据库。我不知道为什么我收到此错误信息无法使用mysqli连接到数据库
Notice: Undefined variable: dbOptions on line 21
Catchable fatal error: Argument 1 passed to DB::init() must be of the type array, null given, called on line 21 and defined on line 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));
}
}
?>
我做错了什么?
'$ dbOptions'尚未设置/给定值。这不是'PDO',它是'mysqli'库 – 2014-09-04 11:48:13
如上所述,你在哪里创建'$ dbOptions'数组? – Steve 2014-09-04 11:51:11
PDO是一个特定的php类,用于连接数据库,就像mysqli一样,这就是您的代码似乎正在使用的内容。这个错误是因为你没有在任何地方定义变量$ dbOptions,所以php会给你一个错误,你调用的函数需要这个变量作为一个数组也会显示一个错误 – Lucas 2014-09-04 11:55:01