简体   繁体   中英

Issue connecting to MySQL with PHP

I am trying to connect to MySQL with PHP but i keep getting the following error: "mysqli::__construct(): (HY000/2002): No such file or directory in /Users/markjonathas/Documents/bar/database_connection.php on line 9" I have MAMP downloaded and I am using PHP 7.3.1 and MySQL version 8.0.16.

I have tried to to download Sequel Pro but when I try to connect to the database I get the following error: "MySQL said: Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/lib/plugin/caching_sha2_password.so, 2): image not found"

//code for database_connection.php:
<?php

    $servername = "127.0.0.1:3306";
    $username = "root";
    $password = "-------";
    $database = "barDB";

    function db_connect() {
        $connection = new mysqli($servername, $username, $password, 
$database);
        return $connection;
    }

    function db_disconenct() {
        if(isset($connection)) {
            $connection->close();
        }
    }
?>

//code for connecting to database_connection.php:

<?php
        require_once("database_connection.php");
        $db = db_connect();
?>

To access global variables, you have to declare them as global:

function db_connect() {
    global $connection, $servername, $username, $password, $database; // <<<<<<<<
    $connection = new mysqli($servername, $username, $password, $database);
    return $connection;
}

function db_disconenct() {
    global $connection; // <<<<<
    if(isset($connection)) {
        $connection->close();
    }
}

Read PHP documentation for details.

Create a file and name it as init.php or whatever you want.

<?php

    $db_name = "barDB";
    $mysql_user = "root";
    $mysql_pass = "-------";
    $server_name = "127.0.0.1:3306";

    $con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);

    if(!$con){
        echo "Server Error";
    }else{

    }

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM