1

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();
?>
1

2 Answers 2

0

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{

    }

?>
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.