Building Chinese Web Sites Using PHP - Version 2.20, by Dr. Herong Yang
Archived: mysql_connect() - Creating MySQL Connections
This section describes how to create an 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($database, $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) 2007 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:\herong> \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