如何使mysqli连接功能? [英] How to make mysqli connect function?

查看:48
本文介绍了如何使mysqli连接功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用mysqli将我连接到数据库的函数遇到问题.我的目标是在需要连接的地方键入getConnected();.

I'm having a problem with a function that connects me to the database using mysqli. What I'm aiming to have is to just type getConnected(); where I need the connection.

这是代码:

function getConnected()
{
    $host = 'localhost';
    $user = 'logintest';
    $pass = 'logintest';
    $db = 'vibo';

    $mysqli = new mysqli($host, $user, $pass, $db);

    if ($mysqli->connect_error) {
        die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
    }
}

这是我在调用getConnected()后尝试使用$mysqli时遇到的错误:

This is the error I get when I try to use $mysqli after calling getConnected():

注意:未定义的变量:第19行的C:\ xampp \ htdocs \ xampp \ loginsystem \ index.php中的mysqli

Notice: Undefined variable: mysqli in C:\xampp\htdocs\xampp\loginsystem\index.php on line 19

推荐答案

正如一些用户所建议的(这是最好的方法),返回mysqli实例

As some users have suggested (and is the best way), return the mysqli instance

function getConnected($host,$user,$pass,$db) {

   $mysqli = new mysqli($host, $user, $pass, $db);

   if($mysqli->connect_error) 
     die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

   return $mysqli;
}

示例:

$mysqli = getConnected('localhost','user','password','database');

这篇关于如何使mysqli连接功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆