ADVM420- Class #4 Web Design with PHP and MySQL Adding and Listing from a MySQL Database.

Post on 23-Dec-2015

224 views 0 download

transcript

ADVM420- Class #4Web Design with PHP

and MySQL

Adding and Listing from a MySQL Database

Objectives

Create our first MySQL database table tblSurvey

Create a PHP script to display the data from this table

Create an HTML add form & PHP script system to add new data into the table

What is a Database?

A Database is a storage mechanism A Database is a collection of “tables”

Eg. A Customer, Products, Orders Each table has a number of “fields”

Eg. Name, Address, City, Phone, Age Each field has a specific “datatype”

Eg. Character, Integer, Float, Date Each field may also have “properties”

Auto-increment, index, unique, default

Primary MySQL Datatypes Varchar – variable length character text Text – unlimited length text (memo) Int – 4-byte integer (-32000 to +32000) BigInt – 8-byte(?) integer (huge!) Single – small floating point numbers Double – large floating point numbers Decimal – fixed decimal (money 10,2) Date – Date only DateTime – Combined date and time

Other Database Features

A Database also has a security system. MySQL’s security system is based on a

username, password and host computer MySQL does not yet fully support referential

integrity

We also need a MySQL Database Manager to allow creation & maintenance of: Tables, fields, field properties Users, security, processes, configuration

2 MySQL Database Managers

MySQL Database Administration Systems allow us to manage to our remote databases by creating tables, fields and users. phpMyAdmin

A web-based alternative to MySQL Control Center Download and Install the phpMyAdmin from:

http://www.phpmyadmin.net/

MySQL Control CenterA Window’s based database management system Download and Install the MySQL Control Center from:

http://www.mysql.com/downloads/ An ODBC driver is also available from MySQL.com

MySQL Control Center /phpMyAdmin

Installing phpMyAdmin

To install phpMyAdmin: Download phpMyAdmin from:

http://www.phpmyadmin.net Expand the ZIP file and copy all to:

~yourname/www/phpMyAdmin Configure phpMyAdmin

as shown on next page…

Configuring phpMyAdmin

Find and open the config.inc.php file Modify the following lines:

$cfg['PmaAbsoluteUri'] = 'http://localhost/~FLast/phpMyAdmin/';

$cfg['Servers'][$i]['host'] = ‘localhost'; $cfg['Servers'][$i]['auth_type'] = 'http';

Open phpMyAdmin: http://phpclassdata.floatsintheparade.com

Example: Survey Table

Create a table called tblSurvey that has the following fields and properties:

ID: int 4, auto-increment, primary key Name: varchar 60, required Children: int 4, default 0 Gender: varchar 1, not required Interests: varchar 50, not required AgeGroup: varchar 20, not required Comments: text, not required Modified: timestamp, required

Do not use spaces or special characters in the field names

Test your table by adding two or more rows of data!

MySQL in PHP

MySQL is an extension to PHP you must ensure it is installed

(it is by default) There are a set of ~40 mysql functions:

All are prefixed with mysql_ Approximately 8 are used frequently

Similar to other database extensions: Interbase, PostgreSQL, Oracle & Others

See documentation for details…

What is SQL, anyway?

SQL – Structured Query Language A language for Creating, Reading, Updating and

Deleting data in a database (CRUD)

Using PHP text strings, we need to “build” the required SQL statements and ask MySQL to execute them…

Four essential SQL statements

SELECT – for viewing RecordSets SELECT * FROM tblSurveys

ORDER BY Name; INSERT – for adding records

INSERT INTO tblSurveys (Name, Children) VALUES (‘Bob’,4);

UPDATE – for changing records UPDATE tblSurveys

SET Name=‘Bob’, Children=5WHERE (ID=2)

DELETE – for deleting records DELETE FROM tblSurveys

WHERE (ID=2);

SELECT Queries:Seven Steps to Viewing Data

There are 7 steps to viewing data:1. Connect to the mySQL server

$link = mysql_connect(”host”,”user”,”pass”);2. Select the database to use

mysql_select_db(”db”);3. Build the query you want to execute

$query = "SELECT * FROM my_table"; 4. Execute the query

$result = mysql_query($query);5. Process the results

$line = mysql_fetch_array($result, MYSQL_ASSOC); //Etc.. Free the result set

mysql_free_result($result); Close the connection

1. mysql_close($link);

SELECT Queries:Quick View of a Table…

<?php $link = mysql_connect("host", "user", "password")

or die("Could not connect"); mysql_select_db("my_database") or die("Could not select database");

$query = "SELECT * FROM my_table"; $result = mysql_query($query) or die("Query failed");

print "<table>\n"; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { print "\t<tr>\n"; foreach ($line as $col_value) {

print "\t\t<td>$col_value</td>\n"; } print "\t</tr>\n"; } print "</table>\n";

mysql_free_result($result); mysql_close($link);

?>

INSERT Queries:6 Steps to adding data

There are 6 steps to adding data:Get the users input

Validate it – garbage in garbage out!!Connect to the mySQL server

$link = mysql_connect(”host”,”user”,”pass”);Select the database to use

mysql_select_db(”db”);Build the query to do the insert

$query = “INSERT INTO my_table (field1,field2) VALUES (‘text’,999)";

Execute the query $result = mysql_query($query);

Close the connection mysql_close($link);

INSERT Queries:an example

$link = mysql_connect("my_server", "User", "Pass") or die("Could not connect"); mysql_select_db("my_database") or die("Could not select database");

$query = "INSERT INTO my_table " . " (Name,Children,Gender,Interests,AgeGroup,Comments) " . " VALUES (" . "'" . $name . "'," . $children . "," . "'" . join($gender,’,’) . "'," . "'" . join($interests,’,’) . "'," . "'" . $agegroup . "'," . "'" . $comments . "'" . ")";print “$query<br>”;$result = mysql_query($query) or die(mysql_error());

mysql_close($link);

Formatting your output

So far, our viewing scripts have been very simple – how to produce “pretty” output? Column headings Currency and date formatting Use of Colours

Let’s modify SurveyDump.php to show the data as formatted output Create the new file as: SurveyView.php

SurveyView.php

/* Connecting, selecting database */ $link = mysql_connect("sequel.macewan.ca", "Username", "Password") or die(mysql_error()); mysql_select_db("DBName") or die(mysql_error());

/* Performing SQL query */ $query = "SELECT *,UNIX_TIMESTAMP(Modified) as ModDate FROM tblSurvey ORDER BY Name"; $result = mysql_query($query) or die(mysql_error());

/* Printing results in HTML */ print "<table border=1 width='100%'>\n"; print "<tr bgcolor=#E0E0E0>\n"; print "<th>ID</th>\n"; print "<th>Name</th>\n"; print "<th>Modified</th>\n"; print "</tr>\n"; while ($row_data = mysql_fetch_array($result, MYSQL_ASSOC)) { print "<tr>\n"; print "<td>".$row_data['ID']."&nbsp;</td>\n"; print "<td>".$row_data['Name']."&nbsp;</td>\n"; print "<td>".date("F j, Y g:i a",$row_data['ModDate'])."&nbsp;</td>\n"; print "</tr>\n"; } print "</table>\n";

mysql_free_result($result);

Create a New Table: tblLinks

Create a table called tblLinks that has the following fields and properties:

int_Link_ID: int 4, auto-increment, primary key txt_Title: varchar 60, required url_Hyperlink: varchar 255, required mem_Description: text, not required dat_Modified_Date: Timestamp, automatic txt_Modified_By: varchar 20, required

Self-test: Link Add System

Create a form called LinkAdd.html that will allow a user to add a link to your database, including: Hyperlink, Title, Description

Create a form processing script called LinkSave.php that adds this link to the database, automatically setting: aut_Modified_By to the user’s IP address

Hint: Modify an example from last class

Self-test: List the Links

Modify the listing program to show the hyperlinks in the database Show the links as clickable using <a> tags

Test your system by adding and listing 5 of your favorite links

Discussion

Now we have way too many links:

How will we delete them?

How will we edit them?