PHP DB
PHP DB
PhP/MySQL 1
Table people
people:
userid int
FirstName varchar(30)
LastName varchar(30)
DateOfBirth date
Username varchar(20)
Password varchar(10)
PhP/MySQL 2
Show all users as an HTML table:
create connection to database
<?php
/* Your MySQL username/password go here! */
$username="php";
$password="php";
$database="dbintro";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or
die( "Unable to select database");
PhP/MySQL 3
Show all users as an HTML table:
Send SQL command to database
// define the SQL command
$query = "SELECT * FROM people";
PhP/MySQL 4
Show all users as an HTML table:
Get records and output as a table
// find out how many records we got
$num = mysql_numrows($res);
echo "<table><tr><th>Name</th><th>Username</th></tr>\n";
// show all the records
for ($i=0;$i<$num;$i++) {
$fname = mysql_result($res,$i,'FirstName');
$lname = mysql_result($res,$i,'LastName');
$username = mysql_result($res,$i,'Username');
echo "<tr><td>$fname $lname</td>";
echo "<td>$username</td></tr>\n";
}
echo "</table>\n"; PhP/MySQL 5
Account Creation
● We need a form the user can fill out
– desired name/username/password, etc.
● The form should be submitted to a PHP program that:
– makes sure the username is available (SQL)
– creates the account if possible (SQL)
PhP/MySQL 6
Submission
● Assume we get the following from a form:
– firstname, lastname, username, password
● We need to check to see if the username is
already taken:
PhP/MySQL 9
Creating the new record: INSERT
● To create a new record use the SQL INSERT
command:
$query = "INSERT INTO people SET FirstName='$firstname',
LastName='$lastname', Username='$username',
Password='$password'";
$res = mysql_query($query);
// now make sure it worked (check $res)
PhP/MySQL 10
Quotes
● Whenever you are specifying the value of a
non-numeric value in an SQL expression, you
need to put the value in quotes:
SELECT * FROM people WHERE FirstName='Fred'
● This won't work:
SELECT * FROM people WHERE FirstName=Fred
Needs Quotes!
● You don't need to quote numbers.
PhP/MySQL 11
SQL-Injection
● What if someone enters the name:
Joe'; drop people
PhP/MySQL 12
Avoid SQL injection trouble
● You need to escape all special characters in
anything you put in an SQL query:
Joe'; drop people Joe\'; drop people
$firstname=mysql_real_escape_string($firstname);
PhP/MySQL 13
Login Processing
● Assumes we have a form with username and
password fields.
cartentries:
productid: integer
userid: integer
quantity: integer
PhP/MySQL 15
viewcart.php
● Make sure there is a session:
if ($_SESSION['userid'])
● We could:
– grab all entries in cartentries that match the userid
– for each entry found, look up the product
information.
● Or – use an SQL join
– One query – grab everything we need
PhP/MySQL 16
Cart Query
PhP/MySQL 18