PHP mysqli connect function [closed]

我只是一个虾纸丫 提交于 2019-11-26 18:37:30

问题


I've just started to look into Mysqli and I've understood most of it now, but I'm having a problem with a function that connects me to the database on other pages.

What I'm aiming to have is to just type getConnected(); where i need to connect.

this is the code:

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());
}
}

and this is the error i get:

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

回答1:


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;
}

Example:

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


来源:https://stackoverflow.com/questions/15226019/php-mysqli-connect-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!