FIT3084: (mySQL) Database Access via the WWW
In the previous lecture:
In this lecture:
References
Sebasta, R.W., "Programming the WWW 2009", 5th edition, Pearson, chapter 13.
http://au.php.net/manual/en/ref.mysql.php
About
|
Relational Database Examples
Example 1.
For every attribute of each entity there could be a column with true or false in it.
ID | Type | Scales | Bark | Fur |
1 | fish | true | false | false |
2 | tree | false | true | false |
3 | reptile | true | false | false |
4 | marsupial | false | false | true |
5 | dog | false | false | true |
The table design above is not ideal. It is better to have one attribute such as "distinctive features" and enter relevant data (scales, bark, legs, wings or fur) into it. What if an entity has more than one attribute simultaneously?
Example 2.
A more complete example organisms table.
life_id | common_name | type_id | length |
1 | Murray Cod | 3 | 1 |
2 | Victorian Ash | 6 | 100 |
3 | Coastal Taipan | 5 | 3 |
4 | Hairy-Nosed Wombat | 4 | 1 |
5 | Dingo | 2 | 1.2 |
6 | Laughing Kookaburra | 1 | 0.4 |
The organisms table needs to be used in conjunction with these:
|
|
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
types Abbreviates the names of the organism types. (Indexed from column 3 of the main table) |
features Abbreviates the names of the organism features. |
organism_features Cross-references the primary keys of the organisms with their features. |
regions Abbreviates the habitat locations within Australia. |
organism_regions Cross-references the primary keys of the organisms' habitat range. |
About SQL - Structured Query Language
About mySQL and PHP
Login to mySQL using PHP | mysql_connect(database-host-name, username, password) or die(mysql_error()); |
Select an existing database... | mysql_select_db(database-name) or die(mysql_error()); |
...or create a new database | $query = 'CREATE DATABASE database-name'; mysql_query($query); |
mySQL commands
Here are some SQL commands. The tables listed above will be used to illustrate them.
CREATE DATABASE | CREATE DATABASE database-name; |
Create a new database called wildlife | CREATE DATABASE wildlife; |
CREATE TABLE |
CREATE TABLE table-name |
Create a new table called organisms
|
CREATE TABLE organisms (life_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, type_id INT NOT NULL, common_name CHAR(15) NOT NULL, length REAL); |
DESCRIBE |
DESCRIBE database-name; |
||||||||||||||||||||||||||||||
Describe the database organisms |
DESCRIBE organisms; |
||||||||||||||||||||||||||||||
Output: |
|
SHOW TABLES Shows the tables in the current database |
SHOW TABLES; |
||
Output: |
|
INSERT INTO / VALUES Insert values into a table in the database |
INSERT INTO table-name |
This example inserts the first entry into the organisms table, i.e. "Murray Cod" is inserted into the column called common_name, 3 into type_id and 1 into length. Below we insert the second entry of organisms. If a column specified as NOT NULL is not included in the INSERT command, mySQL will report an error. |
INSERT INTO organisms |
SELECT Select a set of columns from a table in the current database |
SELECT column-names FROM table-names [WHERE condition]; |
||||||||||||
To select all columns of all the entities in the organism table. | SELECT * FROM organisms; |
||||||||||||
Output: |
|
||||||||||||
To select the common_name column of all entities in the organism table with a length less than 10. | SELECT common_name |
||||||||||||
Output: |
|
||||||||||||
A join of two tables is specified by SELECT-ing multiple tables and including a compound WHERE clause. This example selects all columns from all entities in the organisms and types tables where the type is tree. (The types table must be added and its entries inserted before this would work of course!) | SELECT * FROM organisms, types WHERE organisms.type_id = types.type_id AND types.type = 'tree'; |
||||||||||||
Output: |
|
Other Useful mySQL commands.
UPDATE Update any entities in the named table with the specified column value, using the new values listed. |
UPDATE table-name |
DELETE Delete any rows of a table that match the WHERE clause. |
DELETE FROM table-name WHERE column-name=value; |
DROP Delete any entire database or table. The optional IF EXISTS avoids errors in case the table or database doesn't exist. |
DROP (TABLE | DATABASE) [IF EXISTS] name; |
Interpretting mySQL Queries.
mysql_query( ) doesn't return the output shown above directly as XHTML.
It usually returns a table that can be interpretted with the help of a PHP function like this...
function outputResults($result) { // Get the number of rows in the result of the query $num_rows = mysql_num_rows($result); // Get the number of columns in the result of the query $num_fields = mysql_num_fields($result); // Get the first row of the data. // This will be the header row that contains the names of the columns // We will acquire it in the form of an array. $rowData = mysql_fetch_array($result); // Extract from the header the names of the columns $keys = array_keys($rowData); // Create an XHTML table to output the // result of this PHP script to the browser. print "<table border=1>"; print "<tr align='left'>"; // Make the header row... for ($col=0; $col<$num_fields; $col++) { print "<th>"; print $keys[2*$col +1]; // <--------- See note on mySQL result row interpretation below print "</th>"; } print "</tr>"; // Iterate through the data rows for ($row=0; $row<$num_rows; $row++) { print "<tr align='left'>"; // Extract the contents of each data row as an array $rowValues = array_values($rowData); for ($col=0; $col<$num_fields; $col++) { // Extract each value that corresponds to a column $value = $rowValues[2 * $col + 1]); // <--------- See note on mySQL result row interpretation below print "<th>" . $value . "</th>"; } print "</tr>"; // Get the next row of data $rowData = mysql_fetch_array($result); } print "</table>"; } |
mySQL Result Row Interpretation
PHP arrays are hashes.
The results (confusingly) of a mySQL query therefore contain double sets of elements, one with a numeric key, and one with a string key.
E.g. The result that would be returned for a SELECT that matches the first data row of the types table |
|
would be: | (0,1), (type_id, 1), (1, bird), (type, bird) |
If this data was stored in $result then:
..so the result rows have twice as many elements as there are fields in the result. To neatly extract the data once we must extract every second entry of the table. This explains the highlighted lines in the example above. I.e... |
print $keys[2*$col +1]; ...and... $value = $rowValues[2 * $col + 1]); |
Example PHP Database Access
©Copyright Alan Dorin 2009