dongpuchao1680 2017-07-24 14:09
浏览 176
已采纳

PHP基本连接mysqli_query错误

just building a simple connection to an SQL DB.

I wrote thise simple connection that is function invoked, all of the PHP core API functions are mysqli and not mysql so no mixing is going on, maybe I missed something rather basic here?

The error i'm receiving is: Warning: mysqli_query() expects parameter 1 to be mysqli, null given in G:\xampp\htdocs\phpBackToBasics\connect.php on line 29

I put a vardump to check $connection and it's returned true by 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';
}
  • 写回答

1条回答 默认 最新

  • dongliao3742 2017-07-24 14:20
    关注

    Change these lines:

    static $connection;
    if (isset($connection)) {
    

    as below:

    static $connection = null;
    if ($connection == null) {
    

    Your code checks if connection is there, try to connect. Instead it should check if connection isn't there, try to connect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失