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.

Table of Contents

 About This Book

 PHP Installation on Windows Systems

 Integrating PHP with Apache Web Server

 charset="*" - Encodings on Chinese Web Pages

 Chinese Characters in PHP String Literals

 Multibyte String Functions in UTF-8 Encoding

 Input Text Data from Web Forms

 Input Chinese Text Data from Web Forms

 MySQL - Installation on Windows

MySQL - Connecting PHP to Database

 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

 MySQL - Character Set and Encoding

 MySQL - Sending Non-ASCII Text to MySQL

 Retrieving Chinese Text from Database to Web Pages

 Input Chinese Text Data to MySQL Database

 References

 PDF Printing Version

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