Building Chinese Web Sites using PHP - Version 2.14, by Dr. Herong Yang
mysql_connect() - Creating MySQL Connections
This section describes how to create a object to represent the connection to a MySQL server.
If you want perform any database transactions to a MySQL server, you must create a connection object first by calling the mysql_connect() function. A MySQL server may have multiple databases, so you also need to select a database as the current target database by calling the mysql_select_db() function.
Here are the calling formats of these two functions:
$con = mysql_connect($server, $username, $password); $ok = mysql_select_db($databaes, $con);
The following script shows you how to connect to a local MySQL server, obtained server information, and closed the connection:
<?php #- MySQL-Connection.php #- Copyright (c) 2015, HerongYang.com, All Rights Reserved. # $server = "localhost"; $username = "Herong"; $password = "TopSecret"; $database = "HerongDB"; $con = mysql_connect($server, $username, $password); $ok = mysql_select_db($database, $con); print("Host Info: ".mysql_get_host_info()."\n"); print("Server Info: ".mysql_get_server_info()."\n"); print("Client Info: ".mysql_get_client_info()."\n"); mysql_close($con); ?>
The output confirms that the connection was created correctly:
C:\>\local\php\php MySQL-Connection.php Host Info: localhost via TCP/IP Server Info: 5.0.45-community-nt Client Info: 5.0.37
Note that many MySQL functions do not take the connection object as input parameters. But they do use the latest connection object implicitly.
Last update: 2015.
Table of Contents