Remote mysql connection

2020-02-01 18:12发布

问题:

I'd been making a web on localhost and when I tried to move it on host it shows me lots of errors. Seems like it can't connect to my local database. Here's the code:

$host = "myip";
$user = "root";
$pass = "";
$db = "mydatabase";

mysql_connect($host, $user, $pass);
mysql_select_db($db);
$on = mysql_fetch_row(mysql_query("SELECT COUNT(online) FROM characters WHERE online=1"));
echo "<br>Online: $on[0]<br><br>";

And here's the output:

Warning: mysql_connect() [function.mysql-connect]: Host 'myip' is not allowed to connect to this MySQL server in * on line 46

Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in * on line 48

Online: 

Thanks for help

回答1:

It's a mysql user permission problem. Create a new user with phpmyadmin for example and set it's host to localhost if you connect from localhost, or % if you are connecting from outside.



回答2:

As Alekc correctly stated, it's a permission problem:

You can do this at the MySQL prompt:

grant all privileges on mydatabase.* 
   to youruser@'your_ip_address' 
   identified by 'your_password';

Followed by a:

flush privileges;

And then try to reconnect again. Keep in mind that:

your_ip_adress: it's not the MySQL server's IP address but the IP address you are connecting from (your web server?) your_password: is the one you must use when establishing the connection on PHP side

Also remember that, even though this solution should work, it's not recommendable granting all privileges to a user that will be used by a web application. You can do the same with fewer permissions.

You can do all this with a nice GUI frontend. I prefer command line.