how to connect to database when server is in Unix

2019-06-14 10:54发布

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

4条回答
欢心
2楼-- · 2019-06-14 11:35

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-14 11:36

Just remove localhost.

define('DB_SERVER', '');

Or:

$connection = mysql_connect(DB_USERNAME, DB_PASSWORD) or die(mysql_error())
查看更多
对你真心纯属浪费
4楼-- · 2019-06-14 11:39

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");
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-06-14 11:43

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');
查看更多
登录 后发表回答