Setting Up a Database in MySQL with PHP

Introduction

PHP has an extensive library of functions to interact with MySQL. Open HTML-Kit, or whatever HTML editor you use, click on the PHP button on the Actions Bar and look at the MySQL drop-down list. See also http://www.php.net/manual/en/ref.mysql.php. After writing several of your own programs, you will likely have used most of these functions.

The patriarch of all PHP functions that deal with MySQL is mysql_query(). Once you are linked to MySQL, you can perform any and all of the SQL commands we learned by inserting them in this function. Mysql_query("update table People set NAME_LAST='Smith' where FLITE_ID='bsmith'") will update the table. Mysql_query('alter table people add COMPONENT char(15) NOT NULL') will add that field to the table.

mysql_query('select * from people') will select all the data, but without further instructions, PHP will not display it on the screen.

PHP has gathered some of the most common tasks as well as some of the more complicated ones into functions to make your life easier. I group the functions into the following categories:


Connecting to MySQL

Here are the PHP functions for connecting to MySQL. Those highlighted in light green are considered advanced and will not be taught here, but the links are still provided for your future reference.

You will likely use only the first two bulleted items.

Mysql_connect() establishes a connection to a MySQL server. It takes the following parameters: [server], [username] and [password]. It returns a MySQL link identifier on success, or FALSE on failure. Here's an example:

<?php $link = @mysql_connect("mysql_host", "userid", "userpassword")     or die("Could not connect"); ?>

$link is the MySQL link identifier. If the connection was successful, this identifier will be used throughout the script in retrieving data. If the connection was unsuccessful, $link=FALSE, and the die function is called. The die function (which is an alias for the exit function) terminates the script and displays its string parameter (in this case, it displays "Could not connect").

Using mysql_close() isn't usually necessary, since any link opened with mysql_connect() closes automatically when the script ends. But if you ever wanted to close the current link, the syntax is:

<?php $link = @mysql_connect("mysql_host", "userid", "userpassword")     or die("Could not connect");  . . . mysql_close($link); ?>

Sending Emails   < <  PREVIOUS   Table of Contents NEXT  > >   Databases

Developed with HTML-Kit
Sandersongs Web Tutorials
Contact the Webmasterwith comments.
©2017, by Bill Sanders, all rights reserved.
This domain had 3,999 different visits in the last 30 days.
435,565 hits on this domain since 24 Nov 2006.
http://www.sandersongs.com/PHPsqlCourse/setupDB1.php
This page was last modified on our server on 4 Jun 2008
and last refreshed on our server at 3:56 am, MST
This file took 0.00887 seconds to process.