Be careful, mysqli_connect() does not return a resource ! It returns an instance of the mysqli class (http://php.net/manual/class.mysqli.php) The old mysql_connect() function did return a resource.
(PHP 5, PHP 7, PHP 8)
mysqli::__construct -- mysqli::connect -- mysqli_connect — Open a new connection to the MySQL server
面向对象风格
$hostname
= ini_get("mysqli.default_host")
, string $username
= ini_get("mysqli.default_user")
, string $password
= ini_get("mysqli.default_pw")
, string $database
= ""
, int $port
= ini_get("mysqli.default_port")
, string $socket
= ini_get("mysqli.default_socket")
)$hostname
= ini_get("mysqli.default_host")
, string $username
= ini_get("mysqli.default_user")
, string $password
= ini_get("mysqli.default_pw")
, string $database
= ""
, int $port
= ini_get("mysqli.default_port")
, string $socket
= ini_get("mysqli.default_socket")
) : void过程化风格
$hostname
= ini_get("mysqli.default_host")
, string $username
= ini_get("mysqli.default_user")
, string $password
= ini_get("mysqli.default_pw")
, string $database
= ""
, int $port
= ini_get("mysqli.default_port")
, string $socket
= ini_get("mysqli.default_socket")
) : mysqli|falseOpens a connection to the MySQL Server.
hostname
Can be either a host name or an IP address. The local host is
assumed when passing the null
value or the string "localhost" to this parameter.
When possible, pipes will be used instead of the TCP/IP protocol.
The TCP/IP protocol is used if a host name and port number are provided together e.g. localhost:3308
.
Prepending host by p:
opens a persistent connection.
mysqli_change_user() is automatically called on
connections opened from the connection pool.
username
The MySQL user name.
password
If not provided or null
, the MySQL server will attempt to authenticate
the user against those user records which have no password only. This
allows one username to be used with different permissions (depending
on if a password is provided or not).
database
If provided will specify the default database to be used when performing queries.
port
Specifies the port number to attempt to connect to the MySQL server.
socket
Specifies the socket or named pipe that should be used.
Note:
Specifying the
socket
parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by thehostname
parameter.
mysqli::__construct() always returns an object which represents the connection to a MySQL Server, regardless of it being successful or not.
mysqli_connect() returns an object which represents the connection to a MySQL Server,
或者在失败时返回 false
.
mysqli::connect() returns null
on success 或者在失败时返回 false
.
If MYSQLI_REPORT_STRICT
is enabled and the attempt to connect
to the requested database fails, a mysqli_sql_exception is thrown.
Example #1 mysqli::__construct() example
面向对象风格
<?php
/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/* Set the desired charset after establishing a connection */
$mysqli->set_charset('utf8mb4');
printf("Success... %s\n", $mysqli->host_info);
过程化风格
<?php
/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');
printf("Success... %s\n", mysqli_get_host_info($mysqli));
以上例程的输出类似于:
Success... localhost via TCP/IP
Example #2 Extending mysqli class
<?php
class FooMysqli extends mysqli {
public function __construct($host, $user, $pass, $db, $port, $socket, $charset) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
parent::__construct($host, $user, $pass, $db, $port, $socket);
$this->set_charset($charset);
}
}
$db = new FooMysqli('localhost', 'my_user', 'my_password', 'my_db', 3306, null, 'utf8mb4');
Example #3 Manual error handling
If error reporting is disabled, the developer is responsible for checking and handling failures
面向对象风格
<?php
error_reporting(0);
mysqli_report(MYSQLI_REPORT_OFF);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_errno) {
throw new RuntimeException('mysqli connection error: ' . $mysqli->connect_error);
}
/* Set the desired charset after establishing a connection */
$mysqli->set_charset('utf8mb4');
if ($mysqli->errno) {
throw new RuntimeException('mysqli error: ' . $mysqli->error);
}
过程化风格
<?php
error_reporting(0);
mysqli_report(MYSQLI_REPORT_OFF);
$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (mysqli_connect_errno()) {
throw new RuntimeException('mysqli connection error: ' . mysqli_connect_error());
}
/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');
if (mysqli_errno($mysqli)) {
throw new RuntimeException('mysqli error: ' . mysqli_error($mysqli));
}
Note:
MySQLnd 总是使用服务器的默认字符集。此字符集在连接握手/认证时发送,并被 mysqlnd 使用。
Libmysqlclient 使用 my.cnf 中的默认字符集或者由在调用 mysqli_init() 之后,mysqli_real_connect() 之前先调用 mysqli_options() 来指定。
Note:
面向对象风格 only: If the connection fails, an object is still returned. To check whether the connection failed, use either the mysqli_connect_error() function or the mysqli->connect_error property as in the preceding examples.
Note:
If it is necessary to set options, such as the connection timeout, mysqli_real_connect() must be used instead.
Note:
Calling the constructor with no parameters is the same as calling mysqli_init().
Note:
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 theSYSTEMROOT
environment variable won't be available and PHP will have problems loading Winsock.
Be careful, mysqli_connect() does not return a resource ! It returns an instance of the mysqli class (http://php.net/manual/class.mysqli.php) The old mysql_connect() function did return a resource.
Just wanted to add a note for anyone looking to use the MySQLi persistent connections feature; it's important to note that PHP opens and retains one connection per database user per process.
What this means is that if you are hosting multiple applications, each with its own database user (as is good practice) then you will end up multiplying the number of connections that PHP may hold open.
For example, if you have PHP configured with a maximum of eight worker processes, and you regularly use four different database users, then your MySQL server will need to accept at LEAST a maximum of 32 connections, or else it will run out.
However, if you would like to minimise the number of connections, what you can do is instead is to open the connection using a "guest" user (with no privileges except logging in) and then use ->change_user() to switch to a more privileged user, before switching back to the guest when you're done. Since all of the connections would therefore belong to the guest user, PHP should only maintain one per worker process.
There's a separate port parameter, unlike mysql_connect. However, using host:port on the host parameter does actually work.
There is a caveat. If the host is 'localhost' then the port is ignored, whether you use a port parameter or the implicit syntax I mentioned above. This is because 'localhost' will make it use unix sockets rather than TCP/IP.
It should be noted that on PHP 7 (v7.0.2 at least), passing the empty string '' for the Port argument while connecting to 'localhost' will prevent the connection from being successful altogether.
To work around this, use 'null'.
Note that if the user name is an empty string, like so:
<?php
mysqli( 'localhost', '', 'password', 'database');
?>
then the object returned will have connect_errno=0 (as of PHP 5.5.9). And, as noted elsewhere here, the same applies to the host name.
Note that if the host name is an empty string, like so:
<?php
mysqli( '', 'user', 'password', 'database');
?>
then the object returned will have connect_errno=0 (as of PHP 5.5.9).
A friend of mine encountered a sudden bug with CMS Piwigo. I discovered that :
- He had a hosting rule to use PHP 5.6.
- The hoster uses 5.6.6, verified using phpinfo();.
- The CMS declared a database name parameter as null.
That gallery CMS was unable to connect to MySQL and left only a warning message about it.
We tried to revert back to PHP 5.5, the CMS worked again.
Then we switched back to 5.6.6 and changed those lines :
$dbname = null;
$mysqli = new mysqli($host, $user, $password, $dbname, $port, $socket);
to
$dbname = ''; // Use an empty string, not null
$mysqli = new mysqli($host, $user, $password, $dbname, $port, $socket);
It worked!
So if you made the same mistake, using null where the manual invites to use an empty string, you should consider correcting your code.
A far more secure and language independent way of connecting to mysql is to use the READ_DEFAULT_FILE options. This passes the workload over to the mysql library, which allows for the configuration file itself to be outside of the scope of the language.
The config file itself is something like this:
[client]
user=user_u
password=user_password
host=dbhost
port=3306
database=the_database
default-character-set=utf8
The following code fragment (in OO mysql_i format)
$sqlconf='/var/private/my.cnf';
$sql = new mysqli;
$sql->init();
$sql->options(MYSQLI_READ_DEFAULT_FILE,$sqlconf);
$sql->real_connect();
mysqli can succeed in surprising ways, depending on the privileges granted to the user. For example,
GRANT USAGE ON *.* TO 'myuser'@'localhost' IDENTIFIED BY PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON `database_a`.* TO 'myuser'@'localhost';
CREATE DATABASE database_b;
<?php
$db = new mysqli('localhost', 'myuser', 'mypassword', 'database_b');
if ($db->connect_error) {
die('Connect Error (' . $db->connect_errno . ') '
. $mysqli->connect_error);
}
printf("SQLSTATE: %s\n", $this->db->sqlstate);
printf("Warning Count: %s\n", $db->warning_count);
$db->close();
?>
Will output:
SQLSTATE: 00000
Warning Count: 0
So, life is good — you're connected to the database and executing mysqli methods. Except, life isn't good, because you aren't actually using database_b because myuser doesn't have any privileges on it. You won't catch this until you try to perform a later operation, when you'll get an error, "MYSQL Error: No database selected", and find yourself scratching your head and thinking "what do you mean, of course I have a database selected; I selected one when I called the constructor".
As a result, you may want to perform an additional check after connecting to mysql, to confirm that you're actually connected not just to the mysql server, but to the actual database:
<?php
$db = new mysqli('localhost', 'myuser', 'mypassword', 'database_b');
if ($db->connect_error) {
die('Connect Error (' . $db->connect_errno . ') '
. $mysqli->connect_error);
} elseif ($result = $db->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
if ($row[0] != 'database_b') {
//oops! We're connected to mysql, but not to database_b
}
}
?>
Please do use set_charset("utf8") after establishing the connection if you want to avoid weird string issues. I do not know why the documentation does not warn you about this kind of stuff.
We had a hard time figuring out what was going on since we were using mb_detect_encoding and it said everything was UTF-8, but of course the display was wrong. If we used iconv from ISO-8859-1 to UTF-8 the strings looked fine, even though everything in the database had the right collation. So in the end, it was the connection that was the filter and although the notes for this function mention default charsets, it almost reads as a sidenote instead of a central issue when dealing with UTF and PHP/MySQL.
Note that on all >=Windows 7 Servers, a host name "localhost" will create a very expensive lookup (~1 Second).
That's because since Windows 7, the hosts file doesn't come with a preconfigured
127.0.0.1 localhost
anymore
So, if you notice a long connection creation, try "127.0.0.1" instead.
If you want to connect via an alternate port (other than 3306), as you might when using an ssh tunnel to another host, using "localhost" as the hostname will not work.
Using 127.0.0.1 will work. Apparently, if you specify the host as "localhost", the constructor ignores the port specified as an argument to the constructor.
If you want to connect to local named pipe on windows and you get error "php_network_getaddresses: getaddrinfo failed: No such host is known. ", even if you using using "." as host, please check your if you are using mysqlnd driver: If this is true, then probably you need to update to version 5.4 of php:
Named pipes support for Windows was added in PHP version 5.4.0.
@ http://php.net/manual/en/mysqlnd.overview.php
Hopefully that will save you some time.
If you get an error like
Can't connect to MySQL server on 'localhost' (10061)
and you use named pipes/socket connections (or aren't sure how you installed the MySQL server) try the following connect command:
<?php
mysqli_connect('.', $user_name, $password, $database_name, null, 'mysql');
?>
The '.' as hostname is absolutely necessary when using named pipes. 'localhost' won't work. 'mysql' is the standard name for the pipe/socket.