Building Chinese Web Sites using PHP
Dr. Herong Yang, Version 2.11

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) 2007 by Dr. Herong Yang, http://www.herongyang.com/
#
  $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.

Sections in This Chapter

php_mysql.dll - Configuring PHP to Use MySQL Module

Commonly Used MySQL Functions

mysql_connect() - Creating MySQL Connections

INSERT INTO - Inserting New Records

SELECT - Running Database Queries

UPDATE - Modifying Database Records

Dr. Herong Yang, updated in 2007
mysql_connect() - Creating MySQL Connections