Sie sind auf Seite 1von 18

Connecting to the MySQL Server

This is just the basic syntax:


$link = mysql_connect("localhost");

This would be used if coming from a log in form:


<html>
<head><title>Connect Server</title></head>
<body>
<?
$link = mysql_connect("localhost",$_POST['username'],$_POST['password']) or
die(mysql_error());
print "Successfully connected.\n";
mysql_close($link);
?>
</body>
</html>

In the code shown above the red and blue syntax is all one line.
The blue portion is for error trapping. (See below).
A simplified version of the code is shown below. It does not include the username, password option.
This code would be used on your PC for site development if you did not specify a username and password when
you set up the MySQL server on windows:
$link = mysql_connect("localhost");

Note: Your webhost will require you to include server name and port settings in your connect statement. The
configuration shown below will work with most servers:
$link = mysql_connect(servername.com:3306,username,password);

The code shown below is used when you require your users to log in to access form processing.
If log in is not required just place the actual values in the connect query statement.
$link = mysql_connect("servername.com:3306",$_POST['username'],$_POST['password']);
IndigoAMPP/HTMLPad 2010 Users
The IndigoAMPP server is set up to allow access and operations for a user named root without a password.
test_db.php
This is the configuration we'll use on our scripts.
<html>
<head><title>Connect Server</title></head>
<body>
<?
$link = mysql_connect("localhost","root","") or die(mysql_error());
print "Successfully connected.\n";
mysql_close($link);
?>
</body>
</html>
To run the script:
HTMLPad 2010 users:
Make sure the IndigoAmpp server is running (Check for icon in system tray)
Use normal File - Open to load test_db.php into the editor
Click Preview on bottom of editor window.
When you run the script you should see a white screen and the words 'Successfully connected' in the upper left
corner.
If you DON'T:
Did you check to see if the server is running? Do you know how?
Did you save the scripts in c:\indigoampp\apache-2.2.11\htdocs folder or a folder inside that folder?
Did you set up Preview - Mappings as instructed in my tutorial?
If you missed any of these steps, you need to STOP and Read My Tutorial on setting up HTMLPad.
If you don't have HTMLPad 2010,
you will have to open your browser and manually type the url as:
http://localhost/test_db.php.

If you were successful, you are ready to Create a Database

Sample Login Form


<form method="POST" action="connect_server.php">
Enter Username: <input type="text" name="username" size="20">
Enter Password:<input type="password" name="password" size="20">
<input type="submit" value="Submit"><input type="reset">
</form>
Error Trapping
To save you from constantly visiting the error log file to find problems in your code , you can make use of a
simple error reporting function provided by the mysql server. Using it with the PHP die function will help to
pinpoint problem areas in your code.
The code shown below could be appended to the end of any mysql function statement.
or die(mysql_error());

Closing the Connection


It is good practice to break the connection with the mysql server when operations have ceased. This simple
procedure is accomplished with the line of code shown below:
mysql_close($link);
Building Your Database on Your PC
In order to build your database on your PC and later Export it to your website requires setting up a localhost server
on your PC and finding an HTML editor that will sync up with the server.
If you use Windows, the process of setting up and running a localhost so that you can test and edit scripts and
build databases is very easy.
I recommend the IndigoAMPP web server and the HTMLPad 2010 HTML editor.
I recently installed IndigoAMPP for Windows on my Vista system and it ran on the first try after installation. Setting
up HTMLPad 2010 to work with it is also an easy process.
I created a little tutorial that shows the whole process including how to start the server after you install it. Go to
Tutorial
Note: The server is FREE and you can try the HTML editor for 30 sessions or 30 days free. If you can't learn to
build your database in that amount of time, don't buy the editor. NO RISK!!
Download the Scripts
The Birthdays Database management files can be downloaded in a zip file.
If using IndigoAMPP download to c:\indigoampp\apache-2.2.11\htdocs.
Extract there and you'll have a birthdays folder inside your htdocs folder. Run the scripts from there.
The package contains an integrated db management system, with a simple interface.
This Instruction file is included in the download.
Download birthdays_db.zip
Creating a Table
A database can contain a multiple number of tables which are arranged in columns and rows. Each table is
supplied with a unique name upon creation.
Fields or columns contained within the table are supplied with definitions for type and length.

Note: If you have accessed this web page via a search engine, you should go back and start on our home page. This tutorial is designed
to be viewed and executed in sequence. Learn to build your database right on your PC and Export it to your website.

CREATE TABLE friends( id INT NOT NULL AUTO_INCREMENT,


PRIMARY KEY(id),
firstname VARCHAR(30),
birthday VARCHAR(20));
In the example shown above, we create a table named friends.

The table contains 3 columns:


a primary key field called id which will be automatically incremented each time a record is added.
a firstname field which will contain a variable number of characters up to 30
a birthday field which will contain a variable number of characters up to 20.
IndigoAMPP Users
This is the actual script found in the birthdays_db download.
It adds a table with 4 columns or fields: id, firstname, lastname and birthday.
You can copy the code right from the page and save it as birthdays_create_table.php or you can save time by
downloading the birthdays_db zip file. (See Instructions below)
If you copy and paste, save it in your C:\indigoampp\apache-2.2.11\htdocs folder or create a new folder within
the htdocs folder to keep things tidy. Save and run it from there.
birthdays_create_table.php
<?
$db="newdb";
$link = mysql_connect("localhost", "root", "");
if (! $link) die("Couldn't connect to MySQL");
mysql_select_db($db , $link) or die("Select DB Error: ".mysql_error());
/* create table */
mysql_query(
"CREATE TABLE birthdays(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
firstname VARCHAR(30),
lastname VARCHAR(30),
birthday VARCHAR(20))") or die(mysql_error());
mysql_close($link);
?>

In the example code shown above, before the table can be created, the database must first be selected using the
code:
mysql_select_db($db , $link)

Running the Script


Running this script will create a table named birthdays in the newdb database.
HTMLPad 2010 users:
With server running,
Load birthdays_create_table.php into the editor window
Click Preview.

If there are no error messages, it means the table was created successfully.
If you want to verify on the PHPMyAdmin panel, the databases listed in the left column of the entry page will
show newdb(1).
If you haven't closed the panel, refresh the PHPMyAdmin page. (right click reload or refresh.)
If you see newdb(1) you are ready to Add Some Records

Building Your Database on Your PC


In order to build your database on your PC and later Export it to your website requires setting up a localhost server
on your PC and finding an HTML editor that will sync up with the server.
If you use Windows, the process of setting up and running a localhost so that you can test and edit scripts and
build databases is very easy.
I recommend the IndigoAMPP web server and the HTMLPad 2010 HTML editor.
I recently installed IndigoAMPP for Windows on my Vista system and it ran on the first try after installation. Setting
up HTMLPad 2010 to work with it is also an easy process.
I created a little tutorial that shows the whole process including how to start the server after you install it. Go to
Tutorial
Note: The server is FREE and you can try the HTML editor for 30 sessions or 30 days free. If you can't learn to
build your database in that amount of time, don't buy the editor. NO RISK!!

Inserting Data into a Table


When we say Insert data, we are talking about adding the actual information in the fields of the table.
For example, an insertion in our table would be a first name, last name and the birth date of a user.
The basic SQL syntax is placed within the mysql query function statement.
mysql_query ();

Note: If you have accessed this web page via a search engine, you should go back and start on our home page. This tutorial is designed
to be viewed and executed in sequence. Learn to build your database right on your PC and Export it to your website.

The SQL syntax is enclosed in double quotes. It supplies the command , the name of the table, the field names
and the values to be added.
"INSERT INTO birthdays (firstname, lastname, birthday) VALUES ('Peggy', 'Donahue'
'June 4, 1956')"
The mysql_query function can be used in many other database operations.
The code for adding data to a table is shown below.
The first example (red) shows the actual VALUES which are added.
The second (blue) shows how to add data parsed from a simple form.
<?
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$birthday=$_POST['birthday'];
$db="newdb";
$link = mysql_connect("localhost");
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link)
or die("Couldn't open $db: ".mysql_error());
mysql_query ("INSERT INTO birthdays (firstname, lastname, birthday) VALUES ('Peggy',
'Donahue', 'June 4, 1956')");
mysql_query ("INSERT INTO birthdays (firstname, lastname, birthday) VALUES
('$firstname', '$lastname','$birthday')");
mysql_close($link);
?>
IndigoAMPP Users
We're going to add information to our fields using two scripts.
The first script is a form and the second script will process the form and add the data to the fields in our table.
Copy the code from this page and save the scripts with the supplied filenames.
If you downloaded the zip file, you can run the scripts by loading the birthdays_insert_form.php script and running
it or you can access the script from the db interface script.
If you are copying and pasting, create both scripts before you run the form script.
HTMLPad 2010 users should know how to run a PHP script from the editor by now.
Load and run the birthdays_insert_form.php script. This script will call the birthdays_insert_record.phpscript
which processes the information from the form.
Add a few records.

birthdays_insert_form.php
<html><head><title>Birthdays Insert Form</title>
<style type="text/css">
td {font-family: tahoma, arial, verdana; font-size: 10pt }
</style>
</head>
<body>
<table width="300" cellpadding="5" cellspacing="0" border="2">
<tr align="center" valign="top">
<td align="left" colspan="1" rowspan="1" bgcolor="64b1ff">
<h3>Insert Record</h3>
<form method="POST" action="birthdays_insert_record.php">
<?
print "Enter Firstname: <input type=text name=firstname size=30><br>\n";
print "Enter Lastname: <input type=text name=lastname size=30><br>\n";
print "Enter Birthday: <input type=text name=birthday size=20><br>\n";
print "<br>\n";
print "<input type=submit value=Submit><input type=reset>\n";
?>
</form>
</td></tr></table>
</body>
</html>
birthdays_insert_record.php
<html><head><title>Birthdays Insert Record</title></head>
<body>

<?
/* Change db and connect values if using online */
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$birthday=$_POST['birthday'];
$db="newdb";
$link = mysql_connect('localhost', 'root' , '');
if (! $link) die(mysql_error());
mysql_select_db($db , $link) or die("Select Error: ".mysql_error());
$result=mysql_query(
"INSERT INTO birthdays (
firstname,
lastname,
birthday) VALUES (
'$firstname',
'$lastname',
'$birthday')") or die("Insert Error: ".mysql_error());
mysql_close($link);
print "Record added\n";
?>

<form method="POST" action="birthdays_insert_form.php">


<input type="submit" value="Insert Another Record">
</form>
<br>

<form method="POST" action="birthdays_dbase_interface.php">


<input type="submit" value="Dbase Interface">
</form>
</body>
</html>

Exporting the Table


If you really want to increase your learning curve, I recommend that you take your first crack at exporting the
birthdays table now. If you don't have a web host yet, you may just want to practice the Export part. If you already
have a web host you can run through the entire process of exporting and then Importing it to your web hosting
account. The more you practice the operation, the more comfortable you'll feel when it comes time to move your
completed project online. Go to Export Table

If you don't feel you are ready, continue to Displaying Records

Please Note
If you have completed the lessons in order, all of the scripts in the birthdays_db download package are active.
They can be run from the birthdays_dbase_interface.php script, with the exception of the birthdays_add_fields.php
script. Don't run it until you've completed all the lessons.
You should complete all of the lessons, before you begin to modify the scripts.
Building Your Database on Your PC
In order to build your database on your PC and later Export it to your website requires setting up a localhost server
on your PC and finding an HTML editor that will sync up with the server.
If you use Windows, the process of setting up and running a localhost so that you can test and edit scripts and
build databases is very easy.
I recommend the IndigoAMPP web server and the HTMLPad 2010 HTML editor.
I recently installed IndigoAMPP for Windows on my Vista system and it ran on the first try after installation. Setting
up HTMLPad 2010 to work with it is also an easy process.
I created a little tutorial that shows the whole process including how to start the server after you install it. Go to
Tutorial
Note: The server is FREE and you can try the HTML editor for 30 sessions or 30 days free. If you can't learn to
build your database in that amount of time, don't buy the editor. NO RISK!!
Displaying the Data
In the script below we'll see how to use the mysql_query function to retrieve records or rows from our birthdays
table.
We'll also be introduced to 2 new mysql functions num_rows and fetch_row.

Note: If you have accessed this web page via a search engine, you should go back and start on our home page. This tutorial is designed
to be viewed and executed in sequence. Learn to build your database right on your PC and Export it to your website.

Most of the script is a repetition of syntax you've already learned. The standard procedures of connecting to the
server and selecting the database will not be explained.
The first line of code we'll look at (excluding the error trap) uses the mysql_query function to SELECT all rows and
fields from the table birthdays.
The asterick is used as a wild card. It is used to retrieve all fields in the table.
The data retrieved is stored in the variable $result.
$result = mysql_query( "SELECT * FROM birthdays" )
If we wanted to retrieve only the last names from our database we would change the code accordingly to:
$result = mysql_query( "SELECT lastname FROM birthdays" )

The next line of code for interpretation uses a new mysql function: mysql_num_rows().
This function simply returns the number of rows or records that have been added to the birthdays table.
Notice that it accesses the information retrieved by the previous mysql_query stored as $result.
$num_rows = mysql_num_rows($result);

The line following this syntax in the script prints the result to the screen.

Embedded in the code that prints the results in table form we find another new mysql function.
The mysql_fetch_row() function grabs an individual record or row from $result and divides it into the original
fields. (id,firstname, lastname, birthday)
$get_info = mysql_fetch_row($result)

A foreach loop is used to print the fields in the cells of our table.
foreach ($get_info as $field)

This script can be used to return the rows of any table or database.
Just replace the database name and table name with the appropriate information.
birthdays_display_records.php
<html>
<head><title>Display Records</title>
</head>
<body>

<?php
/* Change next two lines if using online*/
$db="newdb";
$link = mysql_connect('localhost', 'root', '');

if (! $link) die(mysql_error());
mysql_select_db($db , $link) or die("Couldn't open $db: ".mysql_error());
$result = mysql_query( "SELECT * FROM birthdays" )
or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
print "There are $num_rows records.<br>";
print "<table width=600 border=1>\n";
while ($get_info = mysql_fetch_row($result)){
print "<tr>\n";
foreach ($get_info as $field)
print "\t<td>$field</td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close($link);
?>
<br>

<form method="POST" action="birthdays_dbase_interface.php">


<input type="submit" value="Dbase Interface">
</form>

</body>
</html>
**Notice the error trapping used in this script. First it checks for a server connection. Next it checks to see if the
database newdb exists. Then it checks to see if the table, birthdays exists.
Table Displays As:
There are 2 records.
1 Peggy Donahue June 4, 1956
2 Mark Ambrose March 27, 1971

Please Note
If you have completed the lessons in order, all of the scripts in the birthdays_db download package are active.
They can be run from the birthdays_dbase_interface.php script, with the exception of the birthdays_add_fields.php
script. Don't run it until you've completed all the lessons.
You should complete all of the lessons, before you begin to modify the scripts.
Building Your Database on Your PC
In order to build your database on your PC and later Export it to your website requires setting up a localhost server
on your PC and finding an HTML editor that will sync up with the server.
If you use Windows, the process of setting up and running a localhost so that you can test and edit scripts and
build databases is very easy.
I recommend the IndigoAMPP web server and the HTMLPad 2010 HTML editor.
I recently installed IndigoAMPP for Windows on my Vista system and it ran on the first try after installation. Setting
up HTMLPad 2010 to work with it is also an easy process.
I created a little tutorial that shows the whole process including how to start the server after you install it. Go to
Tutorial
Note: The server is FREE and you can try the HTML editor for 30 sessions or 30 days free. If you can't learn to
build your database in that amount of time, don't buy the editor. NO RISK!!
Updating the Data
The process of updating or editing a record or row of a table makes use of the trusty mysql_query() function.
In the syntax shown below we see that the UPDATE procedure requires the SET and WHERE definitions to
pinpoint the changes. The statement below would require that all 4 fields of the specified row be passed to the
processing script.
Here we also realize the value of including the automatically incremented id field to specify a unique identifier for
each row of the birthdays table.

Note: If you have accessed this web page via a search engine, you should go back and start on our home page. This tutorial is designed
to be viewed and executed in sequence. Learn to build your database right on your PC and Export it to your website.

"UPDATE birthdays SET


firstname='$ud_firstname' ,
lastname='$ud_lastname' ,
birthday='$ud_birthday' WHERE id='$ud_id'"

The Editing Query Form


The ideal query form used for editing records, should display the existing data and allow the user to pick a line
number for editing purposes. The code for displaying data from the previous lesson could be used for this
purpose.
A simple query form might look like the one shown below:
1 Peggy Donahue June 4, 1956
2 Mark Ambrose March 27, 1971

Choose a Line to Edit:


Submit Reset

This is a series of 3 scripts used to make changes to fields in the database.


The first shows the code for a form similar to the one displayed above. It queries the user to enter the line number
of the record they want to change.
birthdays_update_form.php
<html><head><title>Birthdays Update Form</title>
</head>
<body>
<?
/* Change next two lines if using online */
$db="newdb";
$link = mysql_connect('localhost', '', '');
if (! $link)
die(mysql_error());
mysql_select_db($db , $link)
or die("Couldn't open $db: ".mysql_error());
$result = mysql_query( "SELECT * FROM birthdays" )
or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
print "There are $num_rows records.<P>";
print "<table width=600 border=1>\n";
while ($get_info = mysql_fetch_row($result)){
print "<tr>\n";
foreach ($get_info as $field)
print "\t<td>$field</td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close($link);
?>
<br>
<form method="POST" action="birthdays_change_form.php">
<pre>
Enter Id Number to Edit: <input type="text" name="id" size="5">
<input type="submit" value="Submit"><input type="reset">
</pre>
</form>
</body>
</html>
The form shown above calls the next form when an id number is chosen.
The Change Form
The form which allows the user to make changes should display existing information in input boxes for editing. The
code for accomplishing this is shown below.
Once again we make use of the mysql_query and mysql_num_rows functions. Then we create a while loop, insert
a basic html form inside and use PHP echo statements in the value field to display existing data.
We also make use of a new function mysql_result(), which separates each field into resource identifier, index and
value.
We'll use a hidden input text box to pass the id value to the processing form as ud_id
<input type="hidden" name="ud_id" value="<? echo "$id" ?>">

birthdays_change_form.php
<html><head><title>Change Record form</title>
<style type="text/css">
td {font-family: tahoma, arial, verdana; font-size: 10pt }
</style>

</head>
<body>
<?
$id=$_POST['id'];
$db="newdb";
$link = mysql_connect('localhost', '', '');
if (! $link)
die("Couldn't connect to MySQL");

mysql_select_db($db , $link)
or die("Couldn't open $db: ".mysql_error());

$query=" SELECT * FROM birthdays WHERE id='$id'";


$result=mysql_query($query);
$num=mysql_num_rows($result);

$i=0;
while ($i < $num) {
$firstname=mysql_result($result,$i,"firstname");
$lastname=mysql_result($result,$i,"lastname");
$birthday=mysql_result($result,$i,"birthday");
?>
<table width="600" cellpadding="10" cellspacing="0" border="2">
<tr align="center" valign="top">
<td align="center" colspan="1" rowspan="1" bgcolor="#64b1ff">
<h3>Edit and Submit</h3>
<form action="birthdays_change_record.php" method="post">
<input type="hidden" name="ud_id" value="<? echo "$id" ?>">
FirstName:<input type="text" name="ud_firstname" value="<? echo "$firstname"?>"><br>
LastName: <input type="text" name="ud_lastname" value="<? echo "$lastname"?>"><br>
Birthday: <input type="text" name="ud_birthday" value="<? echo "$birthday"?>"><br>
<input type="Submit" value="Update">
</form>
</td></tr></table>

<?
++$i;
}
?>
</body>
</html>
The form shown above accepts the changes and calls the processing form birthdays_change_record.php
The Processing Script
The user makes changes to the desired field or fields and clicks the Submit button to pass the information to the
processing script. The PHP script change_birthdays.php isn't really much more than the first line of code we
presented at the top of the page.
The SET option is used to assign the values received from the previous form to the fields name and birthday
WHERE the ud_id string matches the id field.
birthdays_change_record.php
<html><head><title></title></head>
<body>
<?
$ud_id=$_POST['ud_id'];
$ud_firstname=$_POST['ud_firstname'];
$ud_lastname=$_POST['ud_lastname'];
$ud_birthday=$_POST['ud_birthday'];
$db="newdb";
$link = mysql_connect("localhost", "root", "");
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link)
or die("Couldn't open $db: ".mysql_error());
mysql_query(" UPDATE birthdays SET firstname='$ud_firstname' ,
lastname='$ud_lastname' , birthday='$ud_birthday' WHERE id='$ud_id'");
echo "Record Updated";
mysql_close($link);
?>
</body>
</html>
Building Your Database on Your PC
In order to build your database on your PC and later Export it to your website requires setting up a localhost server
on your PC and finding an HTML editor that will sync up with the server.
If you use Windows, the process of setting up and running a localhost so that you can test and edit scripts and
build databases is very easy.
I recommend the IndigoAMPP web server and the HTMLPad 2010 HTML editor.
I recently installed IndigoAMPP for Windows on my Vista system and it ran on the first try after installation. Setting
up HTMLPad 2010 to work with it is also an easy process.
I created a little tutorial that shows the whole process including how to start the server after you install it. Go to
Tutorial
Note: The server is FREE and you can try the HTML editor for 30 sessions or 30 days free. If you can't learn to
build your database in that amount of time, don't buy the editor. NO RISK!!

Delete a Record
The process of deleting a record makes use once again of the mysql_query function. It uses the SELECT method
with the WHERE definition.

Note: If you have accessed this web page via a search engine, you should go back and start on our home page. This tutorial is designed
to be viewed and executed in sequence. Learn to build your database right on your PC and Export it to your website.

The query form used to access this script would be similar to the one used for editing a record. A list of existing
data would be displayed and below it a form to choose a line for removal. The script is identical to the update form
but calls the script birthdays_delete_record.php.
birthdays_delete_form.php
<html><head><title>Birthdays Update Form</title>
</head>
<body>
<?
/* Change next two lines if using online */
$db="newdb";
$link = mysql_connect('localhost', '', '');
if (! $link)
die(mysql_error());
mysql_select_db($db , $link)
or die("Couldn't open $db: ".mysql_error());
$result = mysql_query( "SELECT * FROM birthdays" )
or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
print "There are $num_rows records.<P>";
print "<table width=600 border=1>\n";
while ($get_info = mysql_fetch_row($result)){
print "<tr>\n";
foreach ($get_info as $field)
print "\t<td>$field</td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close($link);
?>
<br>
<form method="POST" action="birthdays_delet_record.php">
<pre>
Enter Id Number to Edit: <input type="text" name="id" size="5">
<input type="submit" value="Submit"><input type="reset">
</pre>
</form>
</body>
</html>

birthdays_delete_record.php
<?
$id=$_POST['id'];
$db="newdb";
$link = mysql_connect("localhost", "root", "");
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link)
or die("Couldn't open $db: ".mysql_error());
mysql_query("DELETE FROM birthdays WHERE id=$id");
mysql_close($link);
?>
One fallacy of this simple script is that it will remove the id field as part of the record. That means that if you have
10 records and delete the record with id number 5, your existing id fields will be 1 to 4 and 6 to 10. The next time
you add a record it will be added as 11 in the 5 spot.
Building Your Database on Your PC
In order to build your database on your PC and later Export it to your website requires setting up a localhost server
on your PC and finding an HTML editor that will sync up with the server.
If you use Windows, the process of setting up and running a localhost so that you can test and edit scripts and
build databases is very easy.
I recommend the IndigoAMPP web server and the HTMLPad 2010 HTML editor.
I recently installed IndigoAMPP for Windows on my Vista system and it ran on the first try after installation. Setting
up HTMLPad 2010 to work with it is also an easy process.
I created a little tutorial that shows the whole process including how to start the server after you install it. Go to
Tutorial
Note: The server is FREE and you can try the HTML editor for 30 sessions or 30 days free. If you can't learn to
build your database in that amount of time, don't buy the editor. NO RISK!!

Altering Tables
Existing tables can be altered using the mysql_query() function.
You can add or modify fields or columns in an existing table. You can delete fields. You can even delete an entire
table and start over.

Note: If you have accessed this web page via a search engine, you should go back and start on our home page. This tutorial is designed
to be viewed and executed in sequence. Learn to build your database right on your PC and Export it to your website.

Add a Column or Field to a Table


To add a column to an existing table the syntax would be:
mysql_query("ALTER TABLE birthdays ADD street CHAR(30)");
You can also specify where you want to add the field.
mysql_query("ALTER TABLE birthdays ADD street CHAR(30) AFTER birthday");

The simple bit of code shown above would add a new column to the birthdays table named street after birthday.
Type and size are also set in the statement.
You can also add multiple fields:

mysql_query("ALTER TABLE birthdays


ADD street CHAR(30) AFTER birthday,
Add city CHAR(30) AFTER street,
ADD state CHAR(4) AFTER city,
ADD zipcode CHAR(20) AFTER state,
ADD phone CHAR(20) AFTER zipcode");

Modify a Column or Field


Column definitions can be modified using the ALTER method. The following code would change the existing
birthday column from 7 to 15 characters.
mysql_query("ALTER TABLE birthdays CHANGE birthday birthday VARCHAR(15)");
In the example the column to alter is first named and then the new definition is supplied which includes the column
name
.
Remove a Column or Field
Columns can be removed from an existing table. The next example of code would remove the lastname column.
mysql_query("ALTER TABLE birthdays DROP lastname");

Remove a Table
Be careful with this code. It will remove an entire table and all of its contents from your database.
mysql_query("DROP TABLE table_name");

This script is included in the download zip file. If you run it, you will need to add the new fields to all of the existing
scripts.
birthdays_add_fields.php
<HTML><BODY>

<?php
/* Use this script to add new fields or columns to your database.
*To change script change names to the fields you want to add
*You can also change VARCHAR to the type you need and add the size.
*DO NOT Preview this script unless you want to add these fields
*or make changes and then run it
*If you use AFTER specify where you want the field to fall
*/
$db="newdb";
$link = mysql_connect('localhost', 'root', '');
if (! $link)
die(mysql_error());
mysql_select_db($db , $link) or die("Select Error: ".mysql_error());

$result=mysql_query("ALTER TABLE birthdays


ADD street VARCHAR(30) AFTER birthday,
Add city VARCHAR(30) AFTER street,
ADD state VARCHAR(4) AFTER city,
ADD zipcode VARCHAR(20) AFTER state,
ADD phone VARCHAR(20) AFTER zipcode") or die("Alter Error: ".mysql_error());
mysql_close($link);
print "Field added";
?>
<form method="POST" action="birthdays_insert_form.php">
<input type="submit" value="Insert Another Record">
</form>
<br>

<form method="POST" action="birthdays_dbase_interface.php">


<input type="submit" value="Dbase Interface">
</form>

</BODY>
</HTML>

Note: All ofhe operations covered above can be performed from the phpMyAdmin panel.
Building Your Database on Your PC
In order to build your database on your PC and later Export it to your website requires setting up a localhost server
on your PC and finding an HTML editor that will sync up with the server.
If you use Windows, the process of setting up and running a localhost so that you can test and edit scripts and
build databases is very easy.
I recommend the IndigoAMPP web server and the HTMLPad 2010 HTML editor.
I recently installed IndigoAMPP for Windows on my Vista system and it ran on the first try after installation. Setting
up HTMLPad 2010 to work with it is also an easy process.
I created a little tutorial that shows the whole process including how to start the server after you install it. Go to
Tutorial
Note: The server is FREE and you can try the HTML editor for 30 sessions or 30 days free. If you can't learn to
build your database in that amount of time, don't buy the editor. NO RISK!!
PHP MySQL
Interactive Website Design

Build a MySQL Database on Your PC then Export it to Your Website


The combination of PHP and MYSQL, when used together can create some pretty impressive results for dynamic
interactive websites.
Unfortunately, PHP/MySQL has always been a confusing subject for beginner website authors and even some
with experience.
It has always been a hassle to create your database on your web host's server and then use scripts to add data
or records to to the database and provide access for your website users.
This tutorial will show you A BETTER WAY.
I'll show you how, step by step,to build your database and your scripts right on your PC and then Export
everything to your web hosting account after you've worked out all the bugs.
I'll introduce you to 2 tools that will make the experience successful for almost everyone that tries.
The Lessons
The lessons provided in this tutorial will be short and simple. You'll learn to create and manipulate a simple
database of names and birthdates.
1. Connecting to the MySQL Server
2. Creating the Database
3. Creating a Table
4. Adding a Record
5. Displaying Records
6. Updating a Record
7. Deleting a Record
8. Altering Tables
9. Exporting to Your Website

Building Your Database on Your PC


In order to build your database on your PC and later Export it to your website requires setting up a localhost server
on your PC and finding an HTML editor that will sync up with the server.
If you use Windows, the process of setting up and running a localhost so that you can test and edit scripts and
build databases is very easy.
I recommend the IndigoAMPP web server and the HTMLPad 2010 HTML editor.
I recently installed IndigoAMPP for Windows on my Vista system and it ran on the first try after installation. Setting
up HTMLPad 2010 to work with it is also an easy process.
Note=> Windows Vista User: You will need to turn off the Windows User Account security feature when installing
and using both the IndigoAMPP server and the PostCast mailserver (if using to test email scripts).
(Windows Control Panel - User Account) Just uncheck the box when installing and using these tools.
I created a little tutorial that shows the whole process including how to start the server after you install it.
Go to Tutorial (DO THIS BEFORE YOU START THIS TUTORIAL)
Note: The server is FREE and you can try the HTML editor for 30 sessions or 30 days free. If you can't learn to
build your database in that amount of time, don't buy the editor. NO RISK!!
Using Other Editors
You can complete this mini course with an HTML editor other than HTMLPad 2010.
The procedure for looking at your web pages and running scripts will be much more involved.
You will download the scripts to the htdocs folder of the indigoAMPP server.
To run the scripts, you will start the IndigoAMPP server, open your browser and enter the url of the script manually
as:
http://localhost/nameofscript.php
When you get tired of doing that, download a free trial of HTMLPad 2010

Das könnte Ihnen auch gefallen