mysql_connect

(PHP 4, PHP 5)

mysql_connect打开一个到 MySQL 服务器的连接

警告

本扩展自 PHP 5.5.0 起已废弃,并在自 PHP 7.0.0 开始被移除。应使用 MySQLiPDO_MySQL 扩展来替换之。参见 MySQL:选择 API 指南来获取更多信息。用以替代本函数的有:

说明

mysql_connect(
    string $server = ini_get("mysql.default_host"),
    string $username = ini_get("mysql.default_user"),
    string $password = ini_get("mysql.default_password"),
    bool $new_link = false,
    int $client_flags = 0
): resource|false

打开或重复使用一个到 MySQL 服务器的连接。

参数

server

MySQL 服务器。可以包括端口号,例如 "hostname:port",或者到本地套接字的路径,例如对于 localhost 的 ":/path/to/socket"。

如果 PHP 指令 mysql.default_host 未定义(默认情况),则默认值是 'localhost:3306'。 在 SQL 安全模式 时,参数被忽略,总是使用 'localhost:3306'。

username

用户名。默认值由 mysql.default_user 定义。 在 SQL 安全模式 时,参数被忽略,总是使用服务器进程所有者的用户名。

password

密码。默认值由mysql.default_password定义。在 SQL 安全模式 时,参数被忽略,总是使用空密码。

new_link

如果用同样的参数第二次调用 mysql_connect(),将不会建立新连接,而将返回已经打开的连接标识。参数 new_link 改变此行为并使 mysql_connect() 总是打开新的连接,甚至当 mysql_connect() 曾在前面被用同样的参数调用过。

client_flags

client_flags 参数可以是以下常量的组合:MYSQL_CLIENT_SSLMYSQL_CLIENT_COMPRESSMYSQL_CLIENT_IGNORE_SPACEMYSQL_CLIENT_INTERACTIVE。进一步信息见 MySQL 客户端常量

返回值

如果成功则返回一个 MySQL 连接标识, 或者在失败时返回 false

示例

示例 #1 mysql_connect() 示例

<?php
$link
= mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!
$link) {
die(
'Could not connect: ' . mysql_error());
}
echo
'Connected successfully';
mysql_close($link);
?>

示例 #2 mysql_connect() 示例:使用 hostname:port 语法

<?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!
$link) {
die(
'Could not connect: ' . mysql_error());
}
echo
'Connected successfully';
mysql_close($link);

// we connect to localhost at port 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!
$link) {
die(
'Could not connect: ' . mysql_error());
}
echo
'Connected successfully';
mysql_close($link);
?>

示例 #3 mysql_connect() 示例:使用 ":/path/to/socket" 语法

<?php
// we connect to localhost and socket e.g. /tmp/mysql.sock

// variant 1: omit localhost
$link = mysql_connect(':/tmp/mysql', 'mysql_user', 'mysql_password');
if (!
$link) {
die(
'Could not connect: ' . mysql_error());
}
echo
'Connected successfully';
mysql_close($link);


// variant 2: with localhost
$link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password');
if (!
$link) {
die(
'Could not connect: ' . mysql_error());
}
echo
'Connected successfully';
mysql_close($link);
?>

注释

注意:

只要将 server 指定为 "localhost" 或 "localhost:port",MySQL 客户端库会越过此值并尝试连接到本地套接字(Windows 中的名字管道)。如果想用 TCP/IP,应该用 "127.0.0.1" 代替 "localhost"。如果 MySQL 客户端库试图连接到一个错误的本地套接字,则应该在 php.ini 中设置 mysql.default_host 的正确路径并把 server 留空。

注意:

脚本一结束,到服务器的连接就被关闭,除非之前已经明确调用 mysql_close() 关闭了。

注意:

Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock.

参见

添加备注

用户贡献的备注 3 notes

up
1
nicodenboer at yahoo dot com
12 years ago
Be carefull here if you use utf8.

The file db.opt of your database should contain the following lines:
default-character-set=utf8
default-collation=utf8_general_ci

It means that your database is created to use the utf8 characterset.
One way to accomplish this is:
CREATE DATABASE my_database DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

Then, after connecting to it from PHP you should use:
mysql_set_charset("UTF8", $connection);

If you don't do this, you will get ugly problems in case other software is reading and writing to the same database!!!!!!
up
0
VTool
8 years ago
fcgid_module modules/mod_fcgid.so
FcgidMaxRequestLen 209715200
FcgidConnectTimeout 240
FcgidIOTimeout 240
FcgidBusyScanInterval 240
FcgidBusyTimeout 240
# Esta línea instruye al servidor web para que reconozca un tipo nuevo (php)
AddHandler fcgid-script .php
# Esta línea indica al servidor web donde está instalado PHP.
FcgidInitialEnv PHPRC "c:/php"
# Esta línea indica al servidor web que debe ejecutar la aplicación
# php-cgi.exe cuando un cliente (navegador) solicite una página con
# extensión .php
FcgidWrapper "c:/php/php-cgi.exe" .php
# Con esta línea damos los permisos necesarios para que los clientes puedan
# acceder/ejecutar a los archivos .php
<Directory "c:/Apache/htdocs">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride None
Allow from all
</Directory>
up
-5
cory dot mawhorter gmail.com
15 years ago
Hopefully this saves someone some grief.

My dev computer is windows and runs wampserver. I have frequent problems with PHP being unable to connect to MySQL after periods of extreme DB activity.

Long story short, it was because I was not running mysql via named-pipes and Windows was running out of available ports to serve PHP. Apparently, on windows, you have 5000 ports to work with and once they are opened, they remain so for 120 seconds before being released. This causes problems with mysql/networking because a new port is requested for each connection.

You can read more about the problem at:
(Link too long and had to be broken up)
http://dev.mysql.com/doc/refman/5.0/en
/can-not-connect-to-server.html#can-not-connect-to-server-on-windows
?>

Since mysql is on localhost, I can just enable named-pipes (which is how you should have mysql setup if you don't need networking) to get around the problem instead of the workaround listed on that page.

For details, see:
http://dev.mysql.com/tech-resources
/articles/securing_mysql_windows.html
To Top