只需建立与SQL DB的简单连接。
我写了这个函数调用的简单连接,所有PHP核心API函数都是mysqli
而不是mysql
所以没有混合正在进行,也许我错过了一些相当基本的东西?
我收到的错误是:Warning: mysqli_query() expects parameter 1 to be mysqli, null given in G:\xampp\htdocs\phpBackToBasics\connect.php on line 29
我放了一个vardump来检查$connection
,它被mysqli_connect
返回为真。
connection.php
function db_connection()
{
static $connection;
if (isset($connection)) {
$host = 'localhost';
$config = parse_ini_file('config.ini');
$connection = mysqli_connect($host, $config['username'], $config['password'], $config['phpBackToBasics']);
}
if ($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query)
{
$connection = db_connection();
var_dump(print_r($connection)); //<== true.
$result = mysqli_query($connection, $query);
if ($result === false) {
return mysqli_error($connection);
}
return $result;
}
function db_error()
{
$connection = db_connection();
return mysqli_error($connection);
}
create.php
include_once 'connect.php';
$result = db_query("INSERT INTO 'users' ('name', 'email') VALUES ('boolBool', 'bool@bool.com')");
if ($result === false) {
$error = db_error();
echo 'you have an error: '.$error;
} else {
return 'Row has been added';
}
答案 0 :(得分:0)
更改这些行:
static $connection;
if (isset($connection)) {
如下:
static $connection = null;
if ($connection == null) {
您的代码会检查是否存在连接,请尝试连接。相反,它应检查连接是否在那里,尝试连接。