In the next lectures you will learn  What is SQL  How to access mySQL database  How to create a basic mySQL database  How to use some basic queries.

Slides:



Advertisements
Similar presentations
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
Advertisements

Let’s try Oracle. Accessing Oracle The Oracle system, like the SQL Server system, is client / server. For SQL Server, –the client is the Query Analyser.
Introduction to Structured Query Language (SQL)
Objectives Connect to MySQL from PHP
MySQL and PHP By Trevor Adams.
1ISM - © 2010 Houman Younessi Lecture 3 Convener: Houman Younessi Information Systems Spring 2011.
DAT702.  Standard Query Language  Ability to access and manipulate databases ◦ Retrieve data ◦ Insert, delete, update records ◦ Create and set permissions.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
MySQL Dr. Hsiang-Fu Yu National Taipei University of Education
PHP1-1 PHP & SQL Xingquan (Hill) Zhu
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
Databases with PHP A quick introduction. Y’all know SQL and Databases  You put data in  You get data out  You can do processing on it very easily 
Session 5: Working with MySQL iNET Academy Open Source Web Development.
Chapter 5 Introduction to SQL. Structured Query Language = the “programming language” for relational databases SQL is a nonprocedural language = the user.
Chapter 9 SQL and RDBMS Part C. SQL Copyright 2005 Radian Publishing Co.
1 Chapter 8 – Working with Databases spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
INTERNET APPLICATION DEVELOPMENT For More visit:
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
LOGO 1 Lab_02: Basic SQL. 2 Outline  Database Tables  SQL Statements  Semicolon after SQL Statements?  SQL DML and DDL  SQL SELECT Statement  SQL.
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
Structured Query Language. SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems.
INTERNET APPLICATION DEVELOPMENT PRACTICAL ON CONNECTING TO MYSQL.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Dbwebsites 2.1 Making Database backed Websites Session 2 The SQL… Where do we put the data?
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
CS 3630 Database Design and Implementation. Your Oracle Account UserName is the same as your UWP username Followed Not case sensitive Initial.
Comp 519: Web Programming Autumn 2014 Advanced SQL and PHP Advanced queries Querying more than one table Searching tables to find information Aliasing.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
PHP MySQL. SQL: Tables CREATE TABLE tablename { fieldname type(length) extra info,... } Extra info: –NULL (allows nulls in this field) –Not NULL (null.
Introduction to Internet Databases MySQL Database System Database Systems.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
SQL 101 for Web Developers 14 November What is a database and why have one? Tables, relationships, normalization SQL – What SQL is and isn’t – CRUD:
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
1 What is database 2? What is normalization? What is SQL? What is transaction?
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
Most information comes from Chapter 3, MySQL Tutorial: 1 MySQL: Part.
CSC WEB PROGRAMMING IN THE NEXT LECTURES YOU WILL LEARN  WHAT IS SQL  HOW TO ACCESS MYSQL DATABASE  HOW TO CREATE A BASIC MYSQL DATABASE  HOW TO USE.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
SQL. คำสั่ง SQL SQL stands for Structured Query Language is a standard language for accessing and manipulating databases.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Module Review Basic SQL commands: Create Database, Create Table, Insert and Select 2. Connect an SQL Database to PHP 3. Execute SQL Commands in.
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
CHAPTER 10 PHP MySQL Database
IS6146 Databases for Management Information Systems Lecture 3: SQL III – The DDL Rob Gleasure robgleasure.com.
Distribution of Marks For Second Semester Internal Sessional Evaluation External Evaluation Assignment /Project QuizzesClass Attendance Mid-Term Test Total.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
SQL Structured Query Language. SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database.
Web Systems & Technologies
CS 3630 Database Design and Implementation
Chapter 5 Introduction to SQL.
CS320 Web and Internet Programming SQL and MySQL
SQL and SQL*Plus Interaction
Database application MySQL Database and PhpMyAdmin
ISC440: Web Programming 2 Server-side Scripting PHP 3
Chapter 8 Working with Databases and MySQL
COMP519: Web Programming Autumn 2015
Comp 519: Web Programming Autumn 2015
Structured Query Language
Using SQL*Plus.
CS3220 Web and Internet Programming SQL and MySQL
MySQL Database System Installation Overview SQL summary
CS3220 Web and Internet Programming SQL and MySQL
MySQL Database System Installation Overview SQL summary
Presentation transcript:

In the next lectures you will learn  What is SQL  How to access mySQL database  How to create a basic mySQL database  How to use some basic queries  How to use PHP and mySQL COMP519: Web Programming Autumn 2014

Introduction to SQL SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating databases. SQL stands for Structured Query Language using SQL can you can  access a database  execute queries, and retrieve data  insert, delete and update records SQL works with database programs like MS Access, DB2, Informix, MS SQL Server, Oracle, Sybase, mySQL, etc. Unfortunately, there are many different versions. But, they must support the same major keywords in a similar manner such as SELECT, UPDATE, DELETE, INSERT, WHERE, etc. Most of the SQL database programs also have their own proprietary extensions!

The University of Liverpool CS department has a version of mySQL installed on the servers, and it is this system that we use in this course. Most all of the commands discussed here should work with little (or no) change to them on other database systems. A mySQL database has been created for your (Computer Science) account here (if you didn’t have one already for another course), and it is this database that you should use for assignment 4 (the PHP/mySQL assignment). Here at Liverpool...

SQL Database Tables A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. LastNameFirstNameAddressCity HansenOlaTimoteivn 10Sandnes SvendsonToveBorgvn 23Sandnes PettersenKariStorgt 20Stavanger The table above contains three records (one for each person) and four columns ( LastName, FirstName, Address, and City ). For example, a table called "Persons":

SQL Queries With SQL, you can query a database and have a result set returned. LastName Hansen Svendson Pettersen A query like this: SELECT LastName FROM Persons; gives a result set like this: The mySQL database system requires a semicolon at the end of the SQL statement!

SQL Data Languages The Data Definition Language (DDL) part of SQL permits database tables to be created or deleted : CREATE TABLE - creates a new database table ALTER TABLE - alters (changes) a database table DROP TABLE - deletes a database table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index The query and update commands together form the Data Manipulation Language (DML) part of SQL : SELECT - extracts data from a database table UPDATE - updates data in a database table DELETE - deletes data from a database table INSERT INTO - inserts new data into a database table *Here we will use some of them in mySQL

Logging into mySQL Server You can log into our mySQL server from Linux by typing in the prompt bash-2.05b$ mysql -h mysql martin –u martin Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is to server version: Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> From here you can create, modify, and drop tables, and modify the data in your tables. But first, you must specify which database on the server you want to use (you have only one, however). mysql> use martin; Database changed

Technical note You probably don’t need to worry about this, but thought I would mention it here… Most books and on-line tutorials assume the database server is running on the same machine as everything else, and that the user is "root". Neither of these are true here. Wherever you see "localhost", replace it by "mysql" Wherever you see "root", replace it with your username. (Ignore this if you don’t understand it for now, or are not consulting other references.)

Creating a Table You can create a table you might use for the upcoming project. For example, mysql> CREATE TABLE students( -> num INT NOT NULL AUTO_INCREMENT, -> f_name VARCHAR(48), -> l_name VARCHAR(48), -> student_id INT, -> VARCHAR(48), -> PRIMARY KEY(num)); Query OK, 0 rows affected (0.02 sec) *If the server gives you a big ERROR, just try again from the top! Hit Enter after each line (if you want). MySQL doesn’t try to interpret the command itself until it sees a semicolon (;) (The “->” characters you see are not typed by you.)

Viewing The Table Structure Use DESCRIBE to see the structure of a table mysql> DESCRIBE students; | Field | Type | Null | Key | Default | Extra | | num | int(11) | NO | PRI | NULL | auto_increment | | f_name | varchar(48) | YES | | NULL | | | l_name | varchar(48) | YES | | NULL | | | student_id | int(11) | YES | | NULL | | | | varchar(48) | YES | | NULL | |

Inserting Data Using INSERT INTO you can insert a new row into your table. For example, mysql> INSERT INTO students -> Query OK, 1 row affected (0.00 sec) Using SELECT FROM you select some data from a table. mysql> SELECT * FROM students; | num | f_name | l_name | student_id | | | 1 | Russell | Martin | | | row in set (0.00 sec)

Inserting Some More Data You can repeat inserting until all data is entered into the table. mysql> INSERT INTO students -> Query OK, 1 row affected (0.01 sec) mysql> SELECT * FROM students; | num | f_name | l_name | student_id | | | 1 | Russell | Martin | | | | 2 | James | Bond | 7 | | rows in set (0.00 sec) Note: The value “NULL” in the “num” field is automatically replaced by the SQL interpreter as the “auto_increment” option was selected when the table was defined.

Getting Data Out of the Table The SELECT command is the main way of getting data out of a table, or set of tables. SELECT * FROM students; Here the asterisk means to select (i.e. return the information in) all columns. You can specify one or more columns of data that you want, such as SELECT f_name,l_name FROM students; | f_name | l_name | | Russell | Martin | | James | Bond | rows in set (0.00 sec)

Getting Data Out of the Table (cont.) You can specify other information that you want in the query using the WHERE clause. SELECT * FROM students WHERE l_name=‘Bond’; | num | f_name | l_name | student_id | | | 2 | James | Bond | 7 | | row in set (0.00 sec) SELECT student_id, FROM students WHERE l_name=‘Bond’; | student_id | | | 7 | | row in set (0.00 sec)

Altering the Table The ALTER TABLE statement is used to add or drop columns in an existing table. mysql> ALTER TABLE students ADD date DATE; Query OK, 2 rows affected (0.00 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM students; | num | f_name | l_name | student_id | | date | | 1 | Russell | Martin | | | NULL | | 2 | James | Bond | 7 | | NULL | rows in set (0.00 sec)

Updating the Table The UPDATE statement is used to modify data in a table. mysql> UPDATE students SET date=' ' WHERE num=1; Query OK, 1 row affected (0.01 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> SELECT * FROM students; | num | f_name | l_name | student_id | | date | | 1 | Russell | Martin | | | | | 2 | James | Bond | 7 | | NULL | rows in set (0.00 sec) Note that the default date format is “YYYY-MM-DD” and I don’t believe this default setting can be changed.

Deleting Some Data The DELETE statement is used to delete rows in a table. mysql> DELETE FROM students WHERE l_name='Bond'; Query OK, 1 row affected (0.00 sec) mysql> SELECT * FROM students; | num | f_name | l_name | student_id | | date | | 1 | Russell | Martin | | | | row in set (0.00 sec)

The Final Table We’ll first add another column, update the (only) record, then insert more data. mysql> ALTER TABLE students ADD gr INT; Query OK, 1 row affected (0.01 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM students; | num | f_name | l_name | student_id | | date | gr | | 1 | Russell | Martin | | | | NULL | row in set (0.00 sec) mysql> UPDATE students SET gr=3 WHERE num=1; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> SELECT * FROM students; | num | f_name | l_name | student_id | | date | gr | | 1 | Russell | Martin | | | | 3 | row in set (0.00 sec) mysql> INSERT INTO students 11-15', 1);...

The Final Table (cont.)... mysql> INSERT INTO students CURRENT_DATE, 2); Note: CURRENT_DATE is a built-in SQL command which (as expected) gives the current (local) date. mysql> SELECT * FROM students; | num | f_name | l_name | student_id | | date | gr | | 1 | Russell | Martin | | | | 3 | | 5 | Kate | Ash | | | | 3 | | 3 | James | Bond | 7 | | | 1| | 4 | Bob | Jones | | | | 3 | | 6 | Pete | Lofton | 76 | | | 2 | | 7 | Polly | Crackers | 1717 | | | 1| | 8 | Hugh | Milner | | | | 2 | rows in set (0.00 sec) mysql> exit Bye

Other SQL Commands SHOW tables; gives a list of tables that have been defined in the database ALTER TABLE students DROP ; would drop the “ ” column from all records DROP TABLE students; deletes the entire “students” table, and its definition (use the DROP command with extreme care!!) DELETE FROM students; removes all rows from the “students” table (so once again, use the DELETE command with great caution), the table definition remains to be used again A more useful command is something like DELETE FROM students WHERE (num > 5) AND (num <= 10); which selectively deletes students based on their “num” values (for example). HELP; gives the SQL help HELP DROP; gives help on the DROP command, etc.

Backing up/restoring a mySQL database You can back up an entire database with a command such as mysqldump –h mysql –u martin martin > backup.sql (Run from the Unix command line.) This gives a script containing SQL commands to reconstruct the table structure (of all tables) and all of the data in the table(s). To restore the database (from scratch) you can use this type of Unix command: mysql –h mysql –u martin martin < backup.sql (Use with caution, as this can overwrite your database.) Other commands are possible to backup/restore only certain tables or items in tables, etc. if that is what you desire. For example mysqldump –h mysql –u martin martin books clients> backup.sql stores information about the “books” and “clients” tables in the “martin” database.

Putting Content into Your Database with PHP We can simply use PHP functions and mySQL queries together: Host: mysql Database: martin Username: martin Password: ---- Connect to the database server and login (this is the PHP command to do so) mysql_connect("host","username","password"); Choose the database mysql_select_db("database"); Send SQL queries to the server to add, delete, and modify data mysql_query("query"); (use the exact same query string as you would normally use in SQL, without the trailing semi-colon) Close the connection to the database server (to ensure the information is stored properly) mysql_close(); Note: For this to work properly on the UoL server, you must access the PHP script through the cgi server ( for example).

Student Database: data_in.php Putting Data in the DB <?php /*insert students into DB*/ if(isset($_POST["submit"])) { $db = mysql_connect("mysql", "martin"); mysql_select_db("martin"); $date=date("Y-m-d"); /* Get the current date in the right SQL format */ $sql="INSERT INTO students VALUES(NULL,'". $_POST["f_name"]. "','". $_POST["l_name"]. "',". $_POST["student_id"]. ",'". $_POST[" "]. "','". $date. "',". $_POST["gr"]. ")"; /* construct the query */ mysql_query($sql); /* execute the query */ mysql_close(); echo" Thank you. The data has been entered. \n"; echo' Back to registration '. "\n"; echo' View the student lists '."\n"; }

Student Database: data_in.php else { ?> Enter your items into the database First Name: Last Name: ID: Group: <?php } /* end of "else" block */ ?> view the output page

Getting Content out of Your Database with PHP Similarly, we can get some information from a database: Connect to the server and login, choose a database mysql_connect("host","username","password"); mysql_select_db("database"); Send an SQL query to the server to select data from the database into an array $result=mysql_query("query"); Either, look into a row and a fieldname $num=mysql_numrows($result); $variable=mysql_result($result,$i,"fieldname"); Or, fetch rows one by one $row=mysql_fetch_array($result); Close the connection to the database server mysql_close();

Student Database: data_out.php Getting Data out of the DB Student Database Order the full list of students by date, id, or by surname. Or only see the list of students in group 1 2 3

Student Database: data_out.php <?php /*get students from the DB */ $db = mysql_connect("mysql","martin"); mysql_select_db("martin", $db); switch($_GET["order"]){ case 'date': $sql = "SELECT * FROM students ORDER BY date"; break; case 'student_id': $sql = "SELECT * FROM students ORDER BY student_id"; break; case 'l_name': $sql = "SELECT * FROM students ORDER BY l_name"; break; default: $sql = "SELECT * FROM students"; break; } if(isset($_POST["submit"])){ $sql = "SELECT * FROM students WHERE gr=". $_POST["gr"]; } $result=mysql_query($sql); /* execute the query */ while($row=mysql_fetch_array($result)){ echo " Name: ". $row["l_name"]. ', '. $row["f_name"]. " \n"; echo " ID: ". $row["student_id"]. " ". $row[" "]. " Group: ". $row["gr"]. " Posted: ". $row["date"]. " \n"; } mysql_close(); ?> view the output page

On the previous examples, I have done no error checking to verify that the database operations were successful (which should normally be performed). I have also done nothing in regards to database security issues and so forth. (I will say more about this later.) Verifying input/output and database security

Can Do Even More with PHP Can create tables in PHP Can delete rows and columns Can make updates Can make queries to several tables Can get connected to several databases * Find more information on PHP/mySQL

Learning Outcomes In these last lectures you have learned  What is SQL  How to access mySQL database  How to create a basic mySQL database  How to use some basic queries  How to use PHP and mySQL