how to connect to database when server is in Unix

2019-06-14 11:10发布

问题:

I have a problem with the connection to database (phpmyadmin), it just because my server is in UNIX socket. I don't know how to connect to it (I'm stand on window). The code below is work fine, if my server is in TCP/IP.

My code

<?php

define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'xxxxxx');
define('DB_DATABASE', 'sample_db');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE, $connection) or die(mysql_error());
mysql_set_charset("utf8", $connection);

?>

Can anyone tell me how to connect to database, if the server is in UNIX socket?

Thank in advance

回答1:

I'm a bit confused by your question.

I'm stand on window

Do you mean that your PHP code is running on a MSWindows machine?

my server is in UNIX

If the database server and the database client (PHP) are running on different machines then they cannot communicate via UNIX filesystem sockets.

The code below is work fine, if my server is in TCP/IP.

No, either your interpretation or your description of events is incorrect. If you specify 'localhost' as the target host in a libmysql client (including PHP's mysql_ extension) then the client will try to connect via the (Unix) filesystem socket. OTOH. if you specify 127.0.0.1, it will use a TCP socket.

In the former scenario, the client gets the path to the socket from ~/.my.cnf, or in the absence of that file /etc/my.cnf, or if you've compiled the client lib yourself, $PREFIX/etc/my.cnf



回答2:

hostname + : + /path/to/socket is required

code snippet from http://us2.php.net/function.mysql-connect

 $link = mysql_connect('localhost:/path/to/socket', 'mysql_user', 'mysql_password');

in your case

define('DB_SERVER', 'localhost:/path/to/socket');

FYI, if you want to TCP socket

$link = mysql_connect('hostname:port', 'mysql_user', 'mysql_password');


回答3:

Just remove localhost.

define('DB_SERVER', '');

Or:

$connection = mysql_connect(DB_USERNAME, DB_PASSWORD) or die(mysql_error())


回答4:

In Unix you can also connect to server in same manner as

     $con = mysql_connect("host","username","password to connect toserver") or die("!server);
     $db  = mysql_select_db("yourdatabase",$con) or die("!db");