Download ppt - SQL | PHP Tutorial

Transcript
Page 1: SQL | PHP Tutorial

SQL | PHP

Tutorialat 8am. god, it’s early.

Page 2: SQL | PHP Tutorial

SQL introThere are many different versions of SQL available for usage. • Oracle• MySQL• SQLite• DB2• Mimer

The popular ones are Oracle and MySQL with MySQL quickly gaining ground. I’ll be showing you MySQL. The syntax between SQL domains varies little and with google skills you can adjust this knowledge for SQLite, which I’ve never used.

Page 3: SQL | PHP Tutorial

Databases _ creationCREATE TABLE tableName (

name VARCHAR(55),sex CHAR(1),age INT(3),birthdate DATE,salary DECIMAL(10,2),primary key(name)

);

Types of attributes: char, varchar, int, smallint, decimal, date, float, etc.*varchar is a string with varying # of characters. In our example, 55 is the characters longest possible string allowed.*decimal(10,2) indicated 2 places after the decimal point and 10 total digits (including the decimal numbers)

Page 4: SQL | PHP Tutorial

Databases _ creation 2CREATE TABLE tableName (

name VARCHAR(55),sex CHAR(1) NOT NULL,age INT(3),birthdate DATE,salary DECIMAL(10,2) DEFAULT ‘0.00’,primary key(name)

);

Primary key: primary key is a UNIQUE value. For every entry in your database this must be unique and not null and every DB must have one.NOT NULL: column must have a valueDEFAULT: you can set a default value if no other value is inputted for that column.

Page 5: SQL | PHP Tutorial

Databases _ indexed primary keysInstead of specifying a column as a primary key you can have the database create a column of numbers that will automatically increment with each entry inserted into the DB. Example:

CREATE TABLE tableName (id INT AUTO_INCREMENT,name VARCHAR(55),sex CHAR(1),age INT(3),birthdate DATE,salary DECIMAL(10,2),primary key(id)

);

Entry 1 will have 1 as a key. Entry 2 will have 2 and so forth.

Page 6: SQL | PHP Tutorial

Databases _ deletionDROP TABLE tableName;

Page 7: SQL | PHP Tutorial

Databases _ insertionInserting data in the database:INSERT INTO tableName(name,sex,age)VALUES(‘Mr. Freeze’,’M’,42);

Also valid:INSERT INTO tableName(sex,name,age)VALUES(‘F’,’Mr. Freeze’,42);

Order doesn’t matter.

Page 8: SQL | PHP Tutorial

Databases _ the meatAlways in the form of:SELECT ….FROM ….WHERE ….

So select a column from your database.From a databaseWhere x meets y condition.

* Except in the case of modification

Page 9: SQL | PHP Tutorial

Databases _ updating Suppose we want to change Mr. Freeze’s age to 52.

UPDATE tableNameSET age = ’52’WHERE name LIKE ‘Mr. Freeze’

And so forth.

Page 10: SQL | PHP Tutorial

Databases _ aggregates This is the actual meat of using SQL. These are where you set your conditions, narrow down your table into a usable set. Here are the usable functions, I’ll show a quick example with each. The only way to really know this stuff is practice.

Group byCountSumAvgMin/MaxOrder by

Page 11: SQL | PHP Tutorial

Databases _ group by This is the actual meat of using SQL. These are where you set your conditions, narrow down your table into a usable set. Here are the usable functions, I’ll show a quick example with each. The only way to really know this stuff is practice. Group by lumps all the common attributes into one row.

SELECT employee_id, MAX(salary)FROM Works_InGROUP BY dept_id;

* MAX selects the maximum value in its () likewise for MIN

Page 12: SQL | PHP Tutorial

Databases _ count Count counts the number of columns with the specified attribute.

SELECT term, COUNT(course_id)FROM teachesGROUP BY term;

We counted the number of courses taught during x term. AVG & SUM function pretty much the same way.

Page 13: SQL | PHP Tutorial
Page 14: SQL | PHP Tutorial

PHP _ connecting to the dbThis is the basic connect script for accessing your db:

<?phpmysql_connect(“localhost”,”username”,”password”) or die(mysql_error()); ?>

Localhost indicates the current machine. So you’re asking the machine to connect to itself. The die(mysql_error) part says if there’s an error halt everything and display this error. If it errors on this part, it means either your host, username, or password are wrong.

Page 15: SQL | PHP Tutorial

PHP _ error checking w/ echoConsider the connection script again with this modification:

<?phpmysql_connect(“localhost”,”username”,”password”) or die(mysql_error());echo “Connected to database.”?>

Later on you may be unable to differentiate where the error occurred. So while developing your code throw in some echo statements, they just print stuff to the screen. When PHP is done connecting to our database it tell us.

Page 16: SQL | PHP Tutorial

PHP _ select the database.<?phpmysql_connect(“localhost”,”username”,”password”) or die(mysql_error());echo “Connected MySQL!”;

mysql_select_db(“ljlayou_comp353” or die(mysql_error());echo “Connected to database 353”;?>

Page 17: SQL | PHP Tutorial

PHP _ create/drop table<?phpmysql_connect(“localhost”,”username”,”pw”) or die(mysql_error());mysql_select_db(“ljlayou_comp353” or die(mysql_error());

mysql_query(“CREATE TABLE Works_In(…)“) or die(mysql_error());?>

We’re querying PHP to tell MySQL to do something, in this case create the table. The same applies for dropping a table. As you can see our code is being reused over and over. It gets pretty repetitive like this. Again we tell php to stop everything if an error occurs.

Page 18: SQL | PHP Tutorial

PHP _ insertion<?phpmysql_connect(“localhost”,”username”,”pw”) or die(mysql_error());mysql_select_db(“ljlayou_comp353” or die(mysql_error());

mysql_query(“INSERT INTO Works_In(company,position) VALUES(‘McDonalds’,’fry cook’)”);?>

We’re querying PHP to tell MySQL to do something, in this case create the table. The same applies for dropping a table. As you can see our code is being reused over and over. It gets pretty repetitive like this.

Page 19: SQL | PHP Tutorial

PHP _ selecting a tableIn order to manipulate, fetch, etc data from your database you must have PHP remember the result. So we store it in an array (?) to preserve “columns”. PHP variables unlike Java do not need a type declaration. From now on I’ll be omitting the connect stuff.

<?php […]$result = mysql_query(“SELECT * FROM Works_In”) or die(mysql_error());$row = mysql_fetch_array($result);

echo “company: “ .$row[‘company’];echo “position:” .$row[‘position’];?>

From these lines we see that each cell in the area is labeled under the column name. Using this method we can output or even compare data.

Page 20: SQL | PHP Tutorial

PHP _ selecting a tableIn order to manipulate, fetch, etc data from your database you must have PHP remember the result. So we store it in an array (?) to preserve “columns”. PHP variables unlike Java do not need a type declaration. From now on I’ll be omitting the connect stuff.

<?php […]$result = mysql_query(“SELECT * FROM Works_In”) or die(mysql_error());$row = mysql_fetch_array($result);

echo “company: “ .$row[‘company’];echo “position:” .$row[‘position’];?>

From these lines we see that each cell in the area is labeled under the column name. Using this method we can output or even compare data. The ‘*’ symbol in the SELECT statement just means that we select all the columns in the table. The above statement however results in the first row only being shown.

Page 21: SQL | PHP Tutorial

PHP _ selecting a table 2To solve this problem, we loop continuously until there are no more rows to choose from.

<?php […]

while ($row = mysql_fetch_array($result)) {echo “company: “ .$row[‘company’]. “ | “position:” .$row[‘position’];echo “<br/>”;}?>

If you have noticed the ‘.’ symbol signifies a concatenation.

Page 22: SQL | PHP Tutorial

PHP _ the formulaWe looked over it all. Here’s the general formula:

<?php

mysql_connect(“localhost”,”username”,”pw”) or die(mysql_error());mysql_select_db(“databaseName” or die(mysql_error());

$result = mysql_query(yourQuery) or die(mysql_error());$row = mysql_fetch_array($result);

while ($row = mysql_fetch_array($result)) { … };?>

(Show 255 final)

Page 23: SQL | PHP Tutorial
Page 24: SQL | PHP Tutorial

PHP _ form processingTopic job but it’s all good. I’m assuming you know howto create forms in HTML. Else, well, google it. It’s pretty straight forward. So let’s take this form as our example, this is a snippet of the form code:

<form name=“animas” action=“processform.php" method="post”> […]

<b>FUN</b>: <input type="radio" name="extra" value="horns">Horns <input type="radio" name="extra" value="wings">Wings <input type="radio" name="extra" value="mane">Mane <input type="radio" name="extra" value="giraffe">Giraffe Neck

<input type="submit" name="submit" value="imagine it" class="submit" />

</form>

Page 25: SQL | PHP Tutorial

PHP _ form processing 2Our form action tells the form what to do with the data. POST is a method that sends an array of variables, our data. Only when the submit button is pressed is the data sent.

<form name=“animals” action=“processform.php" method="post”> […]<input type="submit" name="submit" value="imagine it" class="submit" /></form>

It is common practice to create a separate file for form processing.

Page 26: SQL | PHP Tutorial

PHP _ form processing 3Our data is now winding through the PHP tubes. Let’s look how it’s processed.

$_POST[‘submit’]if( $dbc = @mysql_connect(‘localhost’,’username’,’pw’)) {

if(!@mysql_select_db(‘database’)) {die(mysql_error());} }

else { die(mysql_error());}

$query = “INSERT INTO animals(id,data,appendages, tail, sound,extra)

VALUES(0,’{$_POST[‘body’]}’,’{$_POST[‘appendages’]}’, […] )”

if(@mysql_query($query) { print “success”;}else { print “you lose”;}

mysql_close();

Page 27: SQL | PHP Tutorial

PHP _ form processing 4Some notes on the previous slide:- ‘@’ symbol means success or halt script.- mysql_close(); it’s very important to close your connection when you’re done