Saturday, December 5, 2009

PHP Connection Script to MySQL

This post will discuss using the XAMPP for Windows tool to install a local Apache web server, PHP, and a MySql database server. I will also show how to connect to MySql by using PHP.

XAMPP can be downloaded from http://www.apachefriends.org/en/xampp-windows.html. Besides a PHP parser and a MySQl database server, XAMPP also includes a ftp server, a mail server and MyPhpAdmin, a web-based php client. There are 3 install options: Basic Package, EXE, and a ZIP file. EXE is a self-extracting RAR archive. The Basic Package is a Windows installer and is one I used.

With the Windows installer, XAMPP is installed in a directory on the C drive. There is a subdirectory called htdocs which is the root folder for loading your html or php files. To view pages in your browser, you must type http://local host or 127.0.0.1 followed by the file name and file extension.

PHP script to connect to MySQL database:
A database connection variable is established through a mysql_connect function. The function contains three parameters, the host system, username, and password. On a local server, the host name would be local host or 127.0.0.1; the username is root and the password is user defined.

An IF conditional tests whether a connection to MySQL occurs. An error message is displayed if there is no connection. Once a connection is established, the you select the database with the mysql_select_db function which takes the connection and the name of the database.

?php #Connection Script to MySQL

$dbc = mysql_connect('hostname', 'username', 'password');
if (!$dbc) {
die('Not connected : ' . mysql_error());
}

// make contacts the current db
$db = mysql_select_db('dbname', $dbc);
if (!$db) {
die ('Can\'t use dbname : ' . mysql_error());
}

?>

No comments:

Post a Comment

Get your own Widget