PHP 7.2.4无法连接到我的MySQL 8.0

时间:2018-04-26 16:27:53

标签: php mysqli database-connection

这是我得到的错误......

  

mysqli_connect()

失败

以及 new mysqli 如果我把这一行放在评论中" $ conn = mysqli_connect ..."我没有收到错误,因为它没有尝试连接到数据库。

Fatal error: Uncaught Error: Call to undefined function Classes\Connection\mysqli_connect() in C:\Apache24\htdocs\ControlePM\Classes\Connection\DBConnect.php:21 Stack trace: #0 C:\Apache24\htdocs\ControlePM\index.php(22): Classes\Connection\DBConnect->connect() #1 {main} thrown in C:\Apache24\htdocs\ControlePM\Classes\Connection\DBConnect.php on line 21

这是我的连接代码

我尝试了 new mysqli 同样的错误。

<?php
    namespace Classes\Connection;
    class DBConnect
    {
    var $host;
    var $username;
    var $password;
    var $database;
    public $dbc;
    public $connInfo=FALSE;

    public function __construct(){
        $this->host = 'localhost:3306';
        $this->username = 'root';
        $this->password = 'MyPassWord';
        $this->database = 'MyDB';
    }
    public function connect()
    {
        $conn = mysqli_connect($this->host,$this->username,$this->password,$this->database); 

    if (! $conn) {
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
        exit;
    }
    echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
    echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
    mysqli_close($conn);
    }
?>

的index.php

<?php 
require_once ('Classes/Connection/DBConnect.php'); 
$conn = new DBConnect();
$conn->connect();

if (! $conn->connInfo){
    $result = "Connection failed";
}
else $result = "Connection Succes";
?>

我错过了什么?

2 个答案:

答案 0 :(得分:2)

您正在使用命名空间,因此您需要指定它在全局命名空间mysqli中查找new \mysqli([...]),否则PHP将尝试在您当前的命名空间中查找mysqli(你班上指定的那个。)

其次,您可以通过use语句明确“导入”它。

第三,检查mysqli扩展名是否安装的有用方法是执行以下var_dump(function_exists('mysqli_connect'));this回答。

答案 1 :(得分:1)

PHP构建中缺少我的mysqli

在PHP.ini文件中,“extension = mysqli”被评论