Mysql tutorial database tutorial connectionMysql_connect() Usage of functions
Definition and usage
The mysql_connect () function opens a non-persistent MySQL connection.
Syntax
Mysql_connect (server, user, pwd, newlink, clientflag)
Resource mysql_connect ([string server [, string username [, string password [, bool new_link [, int client_flags])
<? Php tutorial
Try {
$ Mysqlhost = "localhost ";
$ Mysqluser = "root ";
$ Mysqlpass = "";
If ($ db = mysql_connect ($ mysqlhost, $ mysqluser, $ mysqlpass )){
Echo "Successfully connected to the database .";
Mysql_close ($ db );
} Else {
Throw new exception ("Sorry, cocould not connect to mysql .");
}
} Catch (exception $ e ){
Echo $ e-> getmessage ();
}
?>
Tips and comments
Note: When the script ends, the connection to the server is closed, unless mysql_close () has been explicitly called before.
Tip: to create a persistent connection, use the mysql_pconnect () function.
Connect to the mysql database and query the code in detail.
<? Php
Function opendatabase ($ host, $ user, $ pass ){
Try {
If ($ db = mysql_connect ($ host, $ user, $ pass )){
Return $ db;
} Else {
Throw new exception ("Sorry, cocould not connect to mysql .");
}
} Catch (exception $ e ){
Echo $ e-> getmessage ();
}
}
Function closedatabase ($ db ){
Mysql_close ($ db );
}
$ Db = opendatabase ("localhost", "root ","");
Try {
If (! Mysql_select_db ("mydatabase", $ db )){
Throw new exception ("Sorry, database cocould not be opened .");
}
$ Myquery = "insert into mytable (id, title, myvalue) VALUES (0, 'blue', 20 )";
If (mysql_query ($ myquery, $ db )){
Echo "We were successful .";
} Else {
Throw new exception (mysql_error ());
}
} Catch (exception $ e ){
Echo $ e-> getmessage ();
}
Closedatabase ($ db );
?>
Parameters |
Description |
Server |
Optional. Specifies the server to be connected. It can include the port number, for example, "hostname: port", or the path to the local socket, for example, ":/path/to/socket" for localhost ". If the PHP Command mysql. default_host is not defined (the default value is true), the default value is 'localhost: 3306 '. |
User |
Optional. User name. The default value is the user name of the server process owner. |
Pwd |
Optional. Password. The default value is null. |
Newlink |
Optional. If the same parameter is used to call mysql_connect () for the second time, a new connection is not established, but an opened connection ID is returned. The new_link parameter changes this behavior and makes mysql_connect () always open a new connection, even when mysql_connect () was previously called with the same parameter. |
Clientflag |
Optional. The client_flags parameter can be a combination of the following constants:
- MYSQL_CLIENT_SSL-SSL encryption
- MYSQL_CLIENT_COMPRESS-use the compression Protocol
- MYSQL_CLIENT_IGNORE_SPACE-interval after the function name is allowed
- MYSQL_CLIENT_INTERACTIVE-allow interaction timeout and inactivity before closing the connection
|