Está en la página 1de 17

PHP/MySQL tutorial

Karl Quinn 27th November 2004 Ubiquitous Computing M.Sc. 2004 (year one)

Introduction
PHP (Hypertext Preprocessor) - Open source, server-side, scripting language. - Supports databases such as MySQL and Oracle. - http://www.w3schools.com/php/default.asp MySQL (Structured Query Language) - Open source, speedy, scalable, reliable database technology. - http://dev.mysql.com/doc/mysql/en/Tutorial.html

Tutorial Overview
Database (MySQL) - DB creation - Add/delete tables - Add/delete/update records - View/query records Web (PHP) - User front-end - Add & query code - Delete & update code

MySQL & TCD


(1) PuTTY into wilde.cs.tcd.ie on port 22 w/ SSH
- Authenticate with your TCD username and password

(2) ssh macneil.cs.tcd.ie (password as above) (3) Login into your MySQL account mysql uUSERNAME p Enter your MySQL username and password (4) Use MySQL syntax to create and view table(s), records, etc.

Basic MySQL Syntax


SHOW DATABASES; USE database_name; SHOW TABLES; DROP TABLE table_name;

Create MySQL Table


CREATE TABLE user (name varchar(9) NOT NULL, id int(6) NOT NULL, PRIMARY KEY (id), UNIQUE (id) );

Add/Delete/Update Table
INSERT INTO user VALUES (bond, 007); DELETE FROM user WHERE id=007; UPDATE user SET name=BOND WHERE id=007;

Query Database
SELECT * FROM user; SELECT * FROM user WHERE name=BOND; SELECT DISTINCT name FROM user; SELECT name, id FROM user ORDER BY name;

PHP User Front-End


<html> <body> <?php $variable=271004"; echo $variable; ?> </body> </html> Script is executed server side and presented to user via a browser. PHP code is rendered as plain HTML.

PHP Configuration File


Use a securely positioned config file to store variables.
<? // configuration parameters // database configuration $host = "macneill.cs.tcd.ie"; $user = username"; $pass = password"; $db = username_db"; // default contact person $def_contact = Karl"; ?>

Other PHP pages can link to it and use the variables as their own.

PHP Add to DB Code 1


<table cellspacing="5" cellpadding="5"> <form action="addUpdate.php" method="POST"> <tr> <td valign="top"><b><font size="1">Title</font></b></td> <td><textarea name="title" cols="40" rows="2"></textarea></td> </tr> <tr> <td valign="top"><b><font size="1">Authors</font></b></td> <td><textarea name="authors" cols="40" rows="2"></textarea></td> </tr>

<inut type="Submit" name="submit" value="Add"></td></tr> </form> </table>

PHP Add to DB Code 2


<?

include("conf.php");
// form submitted so start processing it

$title = $_POST["title"];
$authors = $_POST["authors"]; // set up error list array & validate text input fields $errorList = array(); $count = 0; if (!$title) { $errorList[$count] = "Invalid entry: Title"; $count++; } // set default value for contact person if (!$contact) { $contact = $def_contact; } // check for errors & if none found... if (sizeof($errorList) == 0) {

$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");


mysql_select_db($db) or die ("Unable to select database!");

$query = "INSERT INTO papers (title, authors, description, comment, super, bibtex, url, genre) VALUES ('$title', '$authors', '$description', '$comment', '$super','$bibtex','$url','$genre')"; $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error());
echo "<font size=-1>Addition successful.<br><br> <a href=papers.php>Go back to the main page</a> | <a href=http://www.cs.tcd.ie/Karl.Quinn/>home</font>"; // close database connection

mysql_close($connection);
} else {// errors occurred} ?>

PHP Query Code


include("conf.php");

$connection = mysql_connect($host, $user, $pass) or die (); mysql_select_db($db) or die ("Unable to select database!"); $query = "SELECT * FROM papers"; $result = mysql_query($query) or die ("Error in query);
?> <table cellpadding="0" cellspacing="0" border="0" width="622"> <tr><td bgcolor="990000"><img src="images/spacer.gif" alt="" height="2"></td></tr> <? // if records present

if (mysql_num_rows($result) > 0)
{ // iterate through resultset & print title with links to edit and delete scripts

while($row = mysql_fetch_object($result))
{ ?> <font size="-2"><a href="edit.php?id=<? echo $row->id; ?>">edit/view</a> | <a href="delete.php?id=<? echo $row->id; ?>">delete</a></font><p>

<font size="-1"><b><? echo $row->title; ?></b><br> <font size="-1"><b>-<? echo $row->authors; ?></b>
<br><a href="<? echo $row->url; ?>" target="_blank"> pdf</a> <br><br><br> </font> <table cellpadding="0" cellspacing="0" border="0" width="622"> <tr><td bgcolor="990000"><img src="images/spacer.gif" alt=" height="2"></td></tr> <? } } // if no records present else{}

mysql_close($connection);
?>

PHP Delete Code


include("conf.php"); // form not yet submitted, display initial form with values pre-filled $id=$_GET['id']; { // open database connection $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); // select database mysql_select_db($db) or die ("Unable to select database!"); // generate and execute query $query = "DELETE FROM papers WHERE id = '$id'"; $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()); // close database connection mysql_close($connection); // print result echo "<font size=-1>Deletion successful. <br><br><a href=papers.php>Go back to the main page</a> | <a href=http://www.cs.tcd.ie/Karl.Quinn/>home</font>"; }

PHP Update Code 1


$id=$_GET['id']; if (!$submit) { $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); mysql_select_db($db) or die ("Unable to select database!"); $query = "SELECT title, authors, description, comment, super, bibtex, url, genre FROM papers WHERE id = '$id'"; $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()) if (mysql_num_rows($result) > 0) { $row = mysql_fetch_object($result); // print form with values pre-filled ?> <table cellspacing="5" cellpadding="5">

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


<input type="hidden" name="id" value="<? echo $id; ?>"> <tr> <td valign="top"><b><font size="-1">Title</font></b></td> <td><textarea name="title" cols="40" rows="2"><? echo $row->title; ?></textarea></td> </tr> <tr> <td valign="top"><b><font size="-1">Authors</font></b></td> <td><textarea name="authors" cols="40" rows="2"><? echo $row >authors; ?></textarea></td> </tr> <tr> <td colspan=2>

<input type="Submit" name="submit" value="Update"></td></tr>


</form> </table>

PHP Update Code 2


include("conf.php"); // form submitted so start processing it $title = $_POST["title"]; $authors = $_POST["authors"]; $id = $_POST["id"]; // set up error list array $errorList = array(); $count = 0; // validate text input fields if (!$title) { $errorList[$count] = "Invalid entry: Title"; $count++; } if (!$contact) { $contact = $def_contact; } // check for errors, if none found... if (sizeof($errorList) == 0) { $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); mysql_select_db($db) or die ("Unable to select database!");

$query = "UPDATE papers SET title = '$title', authors = '$authors', description = '$description', comment = '$comment', super = '$super', bibtex = '$bibtex', url = '$url', genre = '$genre' WHERE id = '$id'";
$result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()); // print result echo "<font size=-1>Update successful.<br><br> <a href=papers.php>Go back to the main page</a> | <a href=http://www.cs.tcd.ie/Karl.Quinn/>home</a></font>"; // close database connection mysql_close($connection); } else{} ?>

Summary
Create MySQL database(s) with tables as required. Create PHP powered webpage for adding, deleting, updating and viewing database information. Be aware or security concerns vis--vis configuration file contents and database info.

También podría gustarte