Using php to remotely connect to a MYSQL Database

时间:2018-03-25 19:07:34

标签: php mysql xampp centos7 remote-access

I'm currently trying through a php to connect to a database in another machine, I'm able to connect already using the command line, like this:

mysql -u root -p'' -h 192.168.2.2 proyectoti

I'm able to manage the database -DDL and DML work-, now the thing is I need to create a simple web page to interact with the database (listing and adding elements to it) and the web page and DB must be in different machines, here is my php:

<?php
//Connect To Database
$hostname='192.168.2.2';
$username='root';
$password='';
$dbname='proyectoti';
$usertable='prueba';
$yourfield = 'prueba';

mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);

$query = 'SELECT * FROM ' . $usertable;
$result = mysql_query($query);
if($result) {
    while($row = mysql_fetch_array($result)){
        print $name = $row[$yourfield];
        echo 'Name: ' . $name;
    }
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}

?>

My database is just for testing and it only has a table called 'prueba' with a field called 'prueba', both machines run CentOS 7 (virtualized), are able to communicate between them (ping), the machine with the DB has installed XAMPP and I already tried a simple page to access something in my demo DB (locally) and it works, the machine that is supposed to have the webpage has httpd installed and php enabled (Already tested this by executing phpinfo(), it works). When I try to load the php on the web browser it just shows a blank page, What should I do? Thank you!

1 个答案:

答案 0 :(得分:0)

I was finally able to connect using php, I did the following:

  1. On the command line I ran: yum install php-mysql and restarted httpd service. I recieved the following error: Connection failed: SQLSTATE[HY000] [2003] Can't connect to MySQL server on (13), so I did as follows:
  2. On the command line I ran: setsebool httpd_can_network_connect_db=1 That let me connect to the database without any problem, I used the PDO example in the following page:

https://www.w3schools.com/php/php_mysql_connect.asp