php连接数据库失败

一个文件调用另一个文件中的函数进行mysql的连接,
会提示报错Warning: Undefined variable $link in E:\webfile\template\docs\Connect.php on line 12

Fatal error: Uncaught TypeError: mysqli_query(): Argument #1 ($mysql) must be of type mysqli, null given in E:\webfile\template\docs\Connect.php:12 Stack trace: #0 E:\webfile\template\docs\Connect.php(12): mysqli_query(NULL, 'insert into use...') #1 E:\webfile\template\docs\Login.php(20): my_error('insert into use...') #2 {main} thrown in E:\webfile\template\docs\Connect.php on line 12

下面是代码

img

img

'; //echo mysqli_error(); exit; } return $res; } ?>

網上的例子。
連接 mysql 之後,如果連接錯誤,顯示錯誤訊息並且停止。


$link = new mysqli("localhost","my_user","my_password","my_db");

// Check connection
if ($link->connect_errno) {
  echo "Failed to connect to MySQL: " . $link ->connect_error;
  exit();
}

另外,function 裡面如果要使用 全局变量 需要使用 $GLOBALS。
$GLOBALS['link'] = new mysqli("localhost","my_user","my_password","my_db");
...
mysqli_query( $GLOBALS['link'], $sql );