SlideShare a Scribd company logo
SQL | PHP   Tutorial at 8am. god, it’s early.
SQL  intro There 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.
Databases _ creation CREATE 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)
Databases _ creation 2 CREATE 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 value DEFAULT:  you can set a default value if no other value is inputted for that column.
Databases _ indexed primary keys Instead 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.
Databases _ deletion DROP TABLE tableName;
Databases _ insertion Inserting 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.
Databases _ the meat Always in the form of: SELECT …. FROM …. WHERE …. So  select  a column from your database. From  a database Where  x meets y condition. *  Except in the case of modification
Databases _ updating  Suppose we want to change Mr. Freeze’s age to 52. UPDATE tableName SET age = ’52’ WHERE name LIKE ‘Mr. Freeze’ And so forth.
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 by Count Sum Avg Min/Max Order by
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_In GROUP BY dept_id; * MAX selects the maximum value in its () likewise for MIN
Databases _ count  Count counts the number of columns with the specified attribute. SELECT term, COUNT(course_id) FROM teaches GROUP BY term; We counted the number of courses taught during x term. AVG & SUM function pretty much the same way.
 
PHP _ connecting to the db This is the basic connect script for accessing your db: <?php mysql_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.
PHP _ error checking w/ echo Consider the connection script again with this modification: <?php mysql_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.
PHP _ select the database. <?php mysql_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”; ?>
PHP _  create/drop table <?php mysql_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.
PHP _  insertion <?php mysql_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.
PHP _  selecting a table In 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.
PHP _  selecting a table In 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.
PHP _  selecting a table 2 To 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.
PHP _  the formula We 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)
 
PHP _  form processing Topic job but it’s all good. I’m assuming you know how to 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&quot; method=&quot;post”>   […] <b>FUN</b>:  <input type=&quot;radio&quot; name=&quot;extra&quot; value=&quot;horns&quot;>Horns  <input type=&quot;radio&quot; name=&quot;extra&quot; value=&quot;wings&quot;>Wings  <input type=&quot;radio&quot; name=&quot;extra&quot; value=&quot;mane&quot;>Mane  <input type=&quot;radio&quot; name=&quot;extra&quot; value=&quot;giraffe&quot;>Giraffe Neck <input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;imagine it&quot; class=&quot;submit&quot; /> </form>
PHP _  form processing 2 Our 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&quot; method=&quot;post”>   […] <input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;imagine it&quot; class=&quot;submit&quot; /> </form> It is common practice to create a separate file for form processing.
PHP _  form processing 3 Our 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();
PHP _  form processing 4 Some 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

More Related Content

What's hot (20)

PDF
basic of desicion control statement in python
nitamhaske
 
PDF
Introduction to web programming with JavaScript
T11 Sessions
 
PPT
Introduction to PHP
Jussi Pohjolainen
 
PPTX
Php & my sql
Norhisyam Dasuki
 
PDF
Zend Certification PHP 5 Sample Questions
Jagat Kothari
 
PPT
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
PPTX
Php Tutorial
pratik tambekar
 
PPT
Javascript
Manav Prasad
 
ODP
Php Learning show
Gnugroup India
 
PDF
Javascript essentials
Bedis ElAchèche
 
PDF
Practice exam php
Yesenia Sánchez Sosa
 
PDF
JavaScript 101 - Class 1
Robert Pearce
 
PPTX
Clean code
Henrique Smoco
 
PDF
Learn php with PSK
Prabhjot Singh Kainth
 
PPT
PHP variables
Siddique Ibrahim
 
PPTX
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
PPT
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
PPT
PHP MySQL Workshop - facehook
Shashank Skills Academy
 
PPT
Javascript
mussawir20
 
PPT
Php mysql
Alebachew Zewdu
 
basic of desicion control statement in python
nitamhaske
 
Introduction to web programming with JavaScript
T11 Sessions
 
Introduction to PHP
Jussi Pohjolainen
 
Php & my sql
Norhisyam Dasuki
 
Zend Certification PHP 5 Sample Questions
Jagat Kothari
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Php Tutorial
pratik tambekar
 
Javascript
Manav Prasad
 
Php Learning show
Gnugroup India
 
Javascript essentials
Bedis ElAchèche
 
Practice exam php
Yesenia Sánchez Sosa
 
JavaScript 101 - Class 1
Robert Pearce
 
Clean code
Henrique Smoco
 
Learn php with PSK
Prabhjot Singh Kainth
 
PHP variables
Siddique Ibrahim
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
PHP MySQL Workshop - facehook
Shashank Skills Academy
 
Javascript
mussawir20
 
Php mysql
Alebachew Zewdu
 

Viewers also liked (20)

PDF
Pemrograman Web with PHP MySQL
djokotingkir999
 
PPTX
Php tutorial
Son Nguyen
 
PDF
PHP MySQL database connections
ayman diab
 
PDF
Modul praktikum javascript
hardyta
 
PPTX
Php & My Sql
cecile59
 
PPTX
PHP tutorial | ptutorial
PTutorial Web
 
PDF
Pemrograman web dengan php my sql
anarkonam
 
DOC
Php mysq l - siapa - takut
SMK Negeri 6 Malang
 
PDF
Perl programming language
Elie Obeid
 
PDF
Php tutorial(w3schools)
Arjun Shanka
 
PDF
Tutorial php membuat Aplikasi Inventaris
Deka M Wildan
 
PPTX
Examination Hall Allocation
Martina Thampan
 
PDF
Ebook PHP - menyelam dan menaklukan samudra php
Puguh Nugroho
 
PPT
Beginners PHP Tutorial
alexjones89
 
PDF
Introduction to PHP
Bradley Holt
 
PPT
Php Presentation
Manish Bothra
 
DOC
Tutorial Pembuatan Aplikasi Website Beserta Databasenya
RCH_98
 
PDF
Php
karousn
 
PPTX
Linux.ppt
onu9
 
Pemrograman Web with PHP MySQL
djokotingkir999
 
Php tutorial
Son Nguyen
 
PHP MySQL database connections
ayman diab
 
Modul praktikum javascript
hardyta
 
Php & My Sql
cecile59
 
PHP tutorial | ptutorial
PTutorial Web
 
Pemrograman web dengan php my sql
anarkonam
 
Php mysq l - siapa - takut
SMK Negeri 6 Malang
 
Perl programming language
Elie Obeid
 
Php tutorial(w3schools)
Arjun Shanka
 
Tutorial php membuat Aplikasi Inventaris
Deka M Wildan
 
Examination Hall Allocation
Martina Thampan
 
Ebook PHP - menyelam dan menaklukan samudra php
Puguh Nugroho
 
Beginners PHP Tutorial
alexjones89
 
Introduction to PHP
Bradley Holt
 
Php Presentation
Manish Bothra
 
Tutorial Pembuatan Aplikasi Website Beserta Databasenya
RCH_98
 
Php
karousn
 
Linux.ppt
onu9
 
Ad

Similar to SQL -PHP Tutorial (20)

PPTX
Mysql
lotlot
 
PDF
Real life-coffeescript
David Furber
 
PPT
Sql 2006
Cathie101
 
PPT
PHP tips by a MYSQL DBA
Amit Kumar Singh
 
PPT
PHP MySQL
Md. Sirajus Salayhin
 
ODP
Mysqlppt
Reka
 
PPT
Diva10
diva23
 
PPT
P H P Part I I, By Kian
phelios
 
PPT
12-security.ppt - PHP and Arabic Language - Index
webhostingguy
 
PPT
Security.ppt
webhostingguy
 
PPT
Open Source Package Php Mysql 1228203701094763 9
isadorta
 
PPTX
Class 8 - Database Programming
Ahmed Swilam
 
ODP
Porting Applications From Oracle To PostgreSQL
Peter Eisentraut
 
PPT
JDBC – Java Database Connectivity
Information Technology
 
PPT
Mysql
Deepa Lakshmi
 
PDF
DataMapper
Yehuda Katz
 
PDF
Sql Injection Myths and Fallacies
Karwin Software Solutions LLC
 
PPT
Php MySql For Beginners
Priti Solanki
 
PPTX
Chapter 2
application developer
 
Mysql
lotlot
 
Real life-coffeescript
David Furber
 
Sql 2006
Cathie101
 
PHP tips by a MYSQL DBA
Amit Kumar Singh
 
Mysqlppt
Reka
 
Diva10
diva23
 
P H P Part I I, By Kian
phelios
 
12-security.ppt - PHP and Arabic Language - Index
webhostingguy
 
Security.ppt
webhostingguy
 
Open Source Package Php Mysql 1228203701094763 9
isadorta
 
Class 8 - Database Programming
Ahmed Swilam
 
Porting Applications From Oracle To PostgreSQL
Peter Eisentraut
 
JDBC – Java Database Connectivity
Information Technology
 
DataMapper
Yehuda Katz
 
Sql Injection Myths and Fallacies
Karwin Software Solutions LLC
 
Php MySql For Beginners
Priti Solanki
 
Ad

More from Information Technology (20)

PDF
Sql Server Security Best Practices
Information Technology
 
PPT
SAN Review
Information Technology
 
PPT
SQL 2005 Disk IO Performance
Information Technology
 
PPT
RAID Review
Information Technology
 
PPT
Review of SQL
Information Technology
 
PPT
Sql 2005 high availability
Information Technology
 
PPT
IIS 7: The Administrator’s Guide
Information Technology
 
PPT
MOSS 2007 Deployment Fundamentals -Part2
Information Technology
 
PPT
MOSS 2007 Deployment Fundamentals -Part1
Information Technology
 
PPT
Clustering and High Availability
Information Technology
 
PDF
F5 beyond load balancer (nov 2009)
Information Technology
 
PPT
WSS 3.0 & SharePoint 2007
Information Technology
 
PPT
SharePoint Topology
Information Technology
 
PDF
Sharepoint Deployments
Information Technology
 
PPT
Microsoft Clustering
Information Technology
 
PDF
Scalable Internet Servers and Load Balancing
Information Technology
 
PPT
Web Hacking
Information Technology
 
PPT
Migration from ASP to ASP.NET
Information Technology
 
Sql Server Security Best Practices
Information Technology
 
SQL 2005 Disk IO Performance
Information Technology
 
Review of SQL
Information Technology
 
Sql 2005 high availability
Information Technology
 
IIS 7: The Administrator’s Guide
Information Technology
 
MOSS 2007 Deployment Fundamentals -Part2
Information Technology
 
MOSS 2007 Deployment Fundamentals -Part1
Information Technology
 
Clustering and High Availability
Information Technology
 
F5 beyond load balancer (nov 2009)
Information Technology
 
WSS 3.0 & SharePoint 2007
Information Technology
 
SharePoint Topology
Information Technology
 
Sharepoint Deployments
Information Technology
 
Microsoft Clustering
Information Technology
 
Scalable Internet Servers and Load Balancing
Information Technology
 
Migration from ASP to ASP.NET
Information Technology
 

Recently uploaded (20)

PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PDF
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
PDF
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PPTX
Wondershare Filmora Crack Free Download 2025
josanj305
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Introducing and Operating FME Flow for Kubernetes in a Large Enterprise: Expe...
Safe Software
 
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
Practical Applications of AI in Local Government
OnBoard
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Wondershare Filmora Crack Free Download 2025
josanj305
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 

SQL -PHP Tutorial

  • 1. SQL | PHP Tutorial at 8am. god, it’s early.
  • 2. SQL intro There 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.
  • 3. Databases _ creation CREATE 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)
  • 4. Databases _ creation 2 CREATE 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 value DEFAULT: you can set a default value if no other value is inputted for that column.
  • 5. Databases _ indexed primary keys Instead 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.
  • 6. Databases _ deletion DROP TABLE tableName;
  • 7. Databases _ insertion Inserting 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.
  • 8. Databases _ the meat Always in the form of: SELECT …. FROM …. WHERE …. So select a column from your database. From a database Where x meets y condition. * Except in the case of modification
  • 9. Databases _ updating Suppose we want to change Mr. Freeze’s age to 52. UPDATE tableName SET age = ’52’ WHERE name LIKE ‘Mr. Freeze’ And so forth.
  • 10. 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 by Count Sum Avg Min/Max Order by
  • 11. 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_In GROUP BY dept_id; * MAX selects the maximum value in its () likewise for MIN
  • 12. Databases _ count Count counts the number of columns with the specified attribute. SELECT term, COUNT(course_id) FROM teaches GROUP BY term; We counted the number of courses taught during x term. AVG & SUM function pretty much the same way.
  • 13.  
  • 14. PHP _ connecting to the db This is the basic connect script for accessing your db: <?php mysql_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.
  • 15. PHP _ error checking w/ echo Consider the connection script again with this modification: <?php mysql_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.
  • 16. PHP _ select the database. <?php mysql_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”; ?>
  • 17. PHP _ create/drop table <?php mysql_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.
  • 18. PHP _ insertion <?php mysql_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.
  • 19. PHP _ selecting a table In 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.
  • 20. PHP _ selecting a table In 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.
  • 21. PHP _ selecting a table 2 To 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.
  • 22. PHP _ the formula We 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)
  • 23.  
  • 24. PHP _ form processing Topic job but it’s all good. I’m assuming you know how to 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&quot; method=&quot;post”> […] <b>FUN</b>: <input type=&quot;radio&quot; name=&quot;extra&quot; value=&quot;horns&quot;>Horns <input type=&quot;radio&quot; name=&quot;extra&quot; value=&quot;wings&quot;>Wings <input type=&quot;radio&quot; name=&quot;extra&quot; value=&quot;mane&quot;>Mane <input type=&quot;radio&quot; name=&quot;extra&quot; value=&quot;giraffe&quot;>Giraffe Neck <input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;imagine it&quot; class=&quot;submit&quot; /> </form>
  • 25. PHP _ form processing 2 Our 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&quot; method=&quot;post”> […] <input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;imagine it&quot; class=&quot;submit&quot; /> </form> It is common practice to create a separate file for form processing.
  • 26. PHP _ form processing 3 Our 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();
  • 27. PHP _ form processing 4 Some 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