Beruflich Dokumente
Kultur Dokumente
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.
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.
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)
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
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";
?>
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>
</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.
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());
$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.
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:
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());
</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