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

 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

 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

Archived Tutorials

 Archived: Download and Install PHP 5.2.2 on Windows

 Archived: Downloading Apache 2.2.4 Binary for Windows

 Archived: Installing Apache 2.2.4 on Windows Systems

 Archived: MySQL 5.0 Download, Installation and Start

 Archived: php_mysql.dll - Configuring PHP to Use MySQL Extension

 Archived: Commonly Used php_mysql.dll Functions

Archived: mysql_connect() - Creating MySQL Connections

 Archived: Character Set Variables on MySQL 5

 Archived: Non-ASCII Test Analysis on MySQL 5

 Archived: Fetching Non-ASCII Text from MySQL 5

 Archived: Sending Text in Latin1 Encoding to MySQL 5

 Archived: Sending Text in UTF8 Encoding to MySQL

 References

 Full Version in PDF/EPUB