PHP script cannot connect to *local* MySQL database

Hi,
I have the free version of Webhost; I wrote a php script to connect to my local MySQL database at home and run the php file in my webhost page. I get the error: Warning: mysqli_connect(): (HY000/2002): Connection timed out
The script run under the Webhost server cannot connect to my local database. Is it because of the free version?
I checked on the forum, but most of the topics relate to connection to Webhost database not the other way around from Webhost to local database.
Thank you.
Mauro

What is your connection code?

Below is my code.
I created a user ‘webPHP’ with password as per below code and granted all privileges connecting from % hostname.

<?php
    $servername = "2.44.53.130"; // my local IP where the MySQL server is
    $username = "webPHP";
    $password = "hdaskjhfasf";  //my fake database password
    $dbname = "DB";  //your database name
    $dbport = "3306";

    $con = mysqli_connect($servername, $username, $password, $dbname, $dbport);

    if (!$con) {
        echo ("Connection failed: ");
    }
    else
    {
        echo ("Connect Successfully");
    }
    
?>

Hi @mprof9
I think it should be like this :slight_smile:

<?php $servername = "localhost"; $username = "username"; $password = "password";

// Create connection $conn = new mysqli($servername, $username, $password);

// Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
echo "Connected successfully"; ?>

Thank you.
I tried your code, but I got:

Connection failed: ProxySQL Error: Access denied for user ‘webPHP’@‘2a02:4780:bad:f00d::e’ (using password: YES)

I am not an expert programmer: I cannot understand why you use localhost if my MySQL server is on IP 2.44.53.130 and the PHP script is executed on Webhost servers.

Thanks

1 Like

You have to find your username.

cPanel -> manage databases -> database table

There is your username and replace it in your code. :slight_smile:

That’s OK for the database I have hosted on Webhost.com: it connects properly
What I would like to know is if I can connect similarly to a MySQL database hosted on my LAN and connect from the PHP script run on my Webhost.com site
Thank you.

Hi @mprof9!

As far as I know, there are no limitations in this aspect: you should be able to connect remotely to other databases.

Just make sure you forward the port 3306 on your LAN. If you are using a router, search online with your router model how to forward port 3306.

OK, thanks.
I made an error in forwarding the port! Now it works!
Thank you all for the help.
Regards

You’re welcome :blush: