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

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 软件供应链安全是跟可靠性有关还是跟安全性有关?
  • ¥15 电脑蓝屏logfilessrtsrttrail问题
  • ¥20 关于wordpress建站遇到的问题!(语言-php)(相关搜索:云服务器)
  • ¥15 【求职】怎么找到一个周围人素质都很高不会欺负他人,并且未来月薪能够达到一万以上(技术岗)的工作?希望可以收到写有具体,可靠,已经实践过了的路径的回答?
  • ¥15 Java+vue部署版本反编译
  • ¥100 对反编译和ai熟悉的开发者。
  • ¥15 带序列特征的多输出预测模型
  • ¥15 Python 如何安装 distutils模块
  • ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行
  • ¥15 资源泄露软件闪退怎么解决?