LIS651 lecture 2 mySQL and PHP mySQL function Thomas Krichel 2005-11-04.

Slides:



Advertisements
Similar presentations
PHP: Date() Function The PHP date() function formats a timestamp to a more readable date and time.
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizards Guide to PHP by David Lash.
LIS651 lecture 3 taming PHP Thomas Krichel
LIS651 lecture 2 mySQL and PHP mySQL functions Thomas Krichel
LIS651 lecture 3 taming PHP Thomas Krichel
LIS651 lecture 2 databases, mySQL and PHP mySQL functions Thomas Krichel
LIS651 lecture 2 mySQL and PHP mySQL function Thomas Krichel
LIS651 lecture 3 functions & sessions Thomas Krichel
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.
Widhy Hayuhardhika NP, S.Kom. Overview of database structure Connecting to MySQL database Selecting the database to use Using the require_once statement.
Session 2Introduction to Database Technology Data Types and Table Creation.
Creating Tables, Setting Constraints, and Datatypes What is a constraint and why do we use it? What is a datatype? What does CHAR mean? Page 97 in Course.
CC SQL Utilities.
MS-Access XP Lesson 1. Introduction to MS-Access Database Management System Software (DBMS) Store data in databases Database is a collection of table.
Database Chapters.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)MySQL Recap.
Day 3 - Basics of MySQL What is MySQL What is MySQL How to make basic tables How to make basic tables Simple MySQL commands. Simple MySQL commands.
Quick-and-dirty.  Commands end in a semi-colon ◦ If you forget, another prompt line shows up  Either continue the command or…  End it with a semi-colon.
Faculty of Sciences and Social Sciences HOPE PHP & MySQL Stewart Blakeway FML 213
PHP (2) – Functions, Arrays, Databases, and sessions.
A Guide to MySQL 3. 2 Objectives Start MySQL and learn how to use the MySQL Reference Manual Create a database Change (activate) a database Create tables.
Structured Query Language SQL: An Introduction. SQL (Pronounced S.Q.L) The standard user and application program interface to a relational database is.
Phonegap Bridge – File System CIS 136 Building Mobile Apps 1.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
1 Working with MS SQL Server. 2 Objectives You will be able to Use Visual Studio for GUI based interactive access to a Microsoft SQL Server database.
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.
LIS651 lecture 7 PHP mySQL Thomas Krichel
Slide 8-1 CHAPTER 8 Using Databases with PHP Scripts: Using MySQL Database with PHP.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
LIS651 lecture 2 mySQL and PHP mySQL function Thomas Krichel
INTERNET APPLICATION DEVELOPMENT For More visit:
ASP.NET Programming with C# and SQL Server First Edition
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
Validated.php
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Week Four CIT 354 Internet II. 2 Objectives Uploading Files to Your Web Site Establishing a Connection Creating a Database Table Common Programming Errors.
PHP meets MySQL.
HAP 709 – Healthcare Databases SQL Data Manipulation Language (DML) Updated Fall, 2009.
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.
Chapter 4 Introduction to MySQL. MySQL “the world’s most popular open-source database application” “commonly used with PHP”
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
LIS651 lecture 6 mySQL Thomas Krichel
Introduction to MySQL Lab no. 10 Advance Database Management System.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
CSC 2720 Building Web Applications Database and SQL.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.
Introduction to CS520/CS596_026 Lecture Two Gordon Tian Fall 2015.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
Advanced Web 2012 Lecture 3 Sean Costain What is a Database? Sean Costain 2012 A database is a structured way of dealing with structured information.
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
1 CS 430 Database Theory Winter 2005 Lecture 11: SQL DDL.
Class 3Intro to Databases Class 4 Simple Example of a Database We’re going to build a simple example of a database, which will allow us to register users.
CSC 2720 Building Web Applications Accessing MySQL from PHP.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
MYSQL AND MYSQL WORKBENCH MIS2502 Data Analytics.
Software-Projekt 2008 Seminarvortrag“Short tutorial of MySql“ Wei Chen Verena Honsel.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Intro to MySQL.
Chapter 5 Introduction to SQL.
CS320 Web and Internet Programming SQL and MySQL
Open Source Server Side Scripting Permissions & Users
Database application MySQL Database and PhpMyAdmin
Chapter 8 Working with Databases and MySQL
CS3220 Web and Internet Programming SQL and MySQL
Chapter 4 Introduction to MySQL.
MySQL Database System Installation Overview SQL summary
CS3220 Web and Internet Programming SQL and MySQL
Presentation transcript:

LIS651 lecture 2 mySQL and PHP mySQL function Thomas Krichel

using mySQL mySQL is installed on wotan. Normally this involves logging into wotan and issuing commands to a character interface. The command would be –mysql -u user -p

uppercase and lowercase Traditionally SQL commands are written with uppercase. mySQL commands are really case-insensitive But variable names in the commands are case- sensitive. I will therefore write them in lowercase.

creating databases CREATE DATABASE a mySQL command to create a new database. Example CREATE DATABASE newbase; creates a database newbase

GRANT This is a command to create users and give them privileges. A simplified general syntax is GRANT privileges ON item TO user_name [IDENTIFIED BY 'password'] [WITH GRANT OPTION] If you use WITH GRANT OPTION, you allow the user to grant other users the privileges that you have given to her.

user privilegesI SELECTallows users to select (read) records from tables. Generally select is a word used for read in databases. INSERTallows users to insert new rows into tables. UPDATEallows users to change values in existing table rows. DELETEallows users to delete table rows (records) INDEX allows user to index tables

user privilegesII ALTERallows users to change the structure of the database. –adding columns –renaming columns or tables –changing the data types of tables DROP allows users to delete databases or tables. In general, the word drop refers to deleting database or tables.

user privilegesIII CREATEallows users to create new databases or tables. If a specific table or database is mentioned in the GRANT statement, users can only create that database or table, which will mean that they have to drop it first. USAGEallows users nothing. This is a useful point to start with if you just want to create a user.

REVOKE This is the opposite of GRANT.

current setup As the super user, I did CREATE DATABASE user_name; GRANT * ON user_name TO user_name IDENTIFIED BY 'secret_word' WITH GRANT OPTION; Here –user_name is your wotan user name –secret_word is your secret word –* means all rights

create a web user You do not want to give the same access rights to people coming in from the web as you have. You do not want to do this. You personally have too many privileges. I have yet to find out how you can create a web user by yourself.

creating tables before you do it, set up some examples on a sheet of paper. Here is an example CREATE TABLE customers (customer_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name CHAR(50) NOT NULL, address CHAR(100) NOT NULL, CHAR(40), state CHAR(2) NOT NULL);

column data types TINYINT can hold a number between -128 and 127 or between 0 to 255. BIT or BOOL are synonyms for the TINYINT. SMALLINT can hold a number between and or 0 and INT can hold a number between -2**31 and 2**31-1 or between 0 and 2**32-1. INTEGER is a synonym for INT. BIGINT can hold a number between -2**63 and 2**61-1 or between 0 and 2**64-1.

column data types: float FLOAT is a floating number on 4 bytes DOUBLE is a floating number on 8 bytes DECIMAL(x,y) where x is the number of digits before the decimal point and y is the number of digits after the decimal point.

column data types: dates DATE is a day from to TIME is a time from -838:59:59 to 838:59:59 DATETIME is a date and time, usually displayed as YYYY-MM-DD HH:MM:SS TIMESTAMP is the number of seconds since at 0 hours. This number may run out in 2037.

field options PRIMARY KEY says that this column is a the primary key. There can be only one such column. Values in the column must be unique. AUTO_INCREMENT can be used on columns that contain integer values. NOT NULL requires the field not to be empty.

USE USE database tells mySQL to start working with the database database. If you have not issued a USE command, you can still address a table table by using database.table, where datebase is the name of your database and table is the name of your table. You are using the dot to link the two together.

addressing database tables columns Let there by a database database with a table table and some column column. Then it is addressed as database.table.column. Parts of this notation can be left out if it is clear what is meant, for example if you have issued USE database before, you can leave out the database part.

INSERT INSERT inserts new rows into a table. In its simples form INSERT INTO table VALUES (value1, value2,..); Example: INSERT INTO products VALUES ('','Neufang Pils',1.23); Note that in the example, I insert the null string in the first column because it is an auto_increment. Mark Sandford says: If you use and auto_increment variable, you may as well have it last.

SELECT This is the SQL statement to select rows from a table. Here is the full syntax: SELECT [options] columns [INTO file_details] FROM table [WHERE conditions] [GROUP BY group_type] [HAVING where_definitions] [ORDER BY order_type] [LIMIT limit_criteria] [PROCEDURE proc_name(arguments)] [lock_options]

columns to SELECT You can have a comma-separated list of columns SELECT name, price FROM products; You can use the star to get all columns SELECT * FROM products;

WHERE condition to SELECT = means equality WHERE id = 3 >, =, <= and != also work as expected IS NULL tests if the value is null IS NOT NULL IN allows you to give a set WHERE state IN ("NY","NJ","CT")

SELECT using multiple tables table1,table2 can be used to join both tables to build a big table that can be searched SELECT orders.id FROM customers, orders WHERE customers.id= 3 This type of join is a Cartesian product aka a full join. For each row of the first table, it adds rows from the second table.

ORDER You can order by a field by saying ORDER BY. You can add ASC or DESC to achieve ascending or descending order. SELECT name, address FROM customers ORDER BY name ASC

column functions AVG(column) give average of the column COUNT(column) gives you a count of non NULL values COUNT(DISTINCT column) gives a count of distinct values MIN(column), MAX(column) STD(column) gives the standard deviation SUM(column) gives the sum of the items

column functions and grouping You can use the function on the columns SELECT AVG(amount) FROM orders; You can group the selection. For example, find the minimum for each customer SELECT MIN(amount) FROM orders GROUP BY customerid; You can use them in conditions with HAVING, such as SELECT customerid FROM orders HAVING AVG(amount) > 10;

LIMIT This can be used to limit the amount of rows. LIMIT This is useful it web sites where you show a selection of the results. This ends the discussion of the SELECT command.

changing values in a row The general syntax is UPDATE [LOW_PRIORITY] [IGNORE] table SET column1=expression1, column2=expression2... [WHERE condition] [ORDER BY order_criteria] [LIMIT number] ; An example is UPDATE students SET = WHERE name='Janice Insinga'; IGNORE instructs to ignore errors. LOW_PRIORITY instructs to delay if the server is busy.

deleting rows The general syntax is DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM table [WHERE condition] [ORDER BY order_criteria] [LIMIT number] Bad example DELETE FROM customers; Good example DELETE FROM customers WHERE customer.name='Thomas Krichel'

PHP mySQL functions We are using here the new version of PHP mySQL function, starting with mysql_ The interface is object-oriented, but can also be accessed in a non-object-oriented way. This is known as the procedural style, in the documentation. You should use the online documentation at

mysql_connect() This is used to establish a connection to the mySQL server. It is typically of the form mysql_connect('host', 'user', 'password'); Example $link= mysql_connect('localhost','boozer','heineken'); You can use localhost as the host name for wotan talking to itself, but you could also connect to other Internet hosts, if you have permission. The function returns a variable of type resource. If there is a mistake, it returns false.

mysql_connect_error () This function does not exist. Do not study this slide. This function returns a string with the last connection error. $link = mysql_connect("localhost", "bad_user", ""); if (!$link) { print "Can't connect to localhost. The error is "; print mysql_connect_error(); print " "; }

mysql_error() This function return the error from the last mySQL command. It returns false if there was no error. $error=mysql_error(); if($error) { print "mySQL error: $error "; } The value returned from that function is a simple string. It is a good idea to check out error messages.

mysql_select_db() This command has the syntax mysql_select_db('database') where database is the name of a database. It returns a Boolean. This tells mySQL that you now want to use the database database. mysql_select_db('beer_shop'); It has the same effect as issuing USE beer_shop; within mySQL.

mysql_query() mysql_query(query) send the query query to mySQL. $link = mysql_connect("localhost", "shop_owner", "bruch"); // you may then add some connection checks $query="SELECT * FROM beer_shop.customers"; $result=mysql_query($query); Note that the query itself does not require a terminating semicolon. The result is in $result.

result of mysql_query() For SELECT, SHOW, DESCRIBE or EXPLAIN mySQL queries, mysql_query() returns a resource that can be further examined with mysql_fetch_array(). For UPDATE, DELETE, DROP and others, mysql_query() returns a Boolean value.

examining resulting rows mysql_fetch_array(result) returns an array that is the result row for the resource resource representing the most recent, or NULL if it the last result is reached. Its results in an array that contains the columns requested both by number and by column name: while($columns=mysql_fetch_array($result)) { print 'name: '.$columns['name']; print 'first column: $columns[0]; }

examining a specific result mysql_data_seek(result, number) sets the array that is returned by mysql_fetch_array to a number number. while($row=mysql_fetch_array($result)) { print 'first column: '.$row[0]; } mysql_data_seek($result,0); // otherwise the second loop would not work while($row=mysql_fetch_array($result)) { print 'first column: '.$row[0]; }

mysql_real_escape_string() mysql_real_escape_string(string) returns a string escaped for the using in mySQL. $name="John O'Guiness"; $s_name=mysql_real_escape_string($name); print $s_name; // prints: John O\'Guiness Note that this function makes a call to mySQL, therefore a connection must be established before the function can be used. This function guards against SQL injections.

mysql_close() This command connection. When it is invoked without an argument, it closes the current connection. This is the happiest command there is, because it means that we have finished. Unfortunately it is not used very often because the mySQL connection is closed automatically when the script finishes running.

extra: sha1() This is a function that calculates a combination of 40 characters from a string. The result of sha1() can not be translated back into the original string. This makes it a good way to store password. –$s_password=sha1($password);

Thank you for your attention! Please switch off machines b4 leaving!

partial INSERT If you are only giving a part of a record, or if you want to enter them in a different order you will have to give a list of column names. INSERT INTO products (name,id) VALUES ('Neufang Pils','');

complicated queries who ordered Bruch Landbock? SELECT customer.id from customers, orders, orders_items, products WHERE customers.id=orders.customer_id AND orders.id=orders_items.order_id AND orders_items.item_id=products_id AND products.name='Bruch Landbock'

left join Another way to join tables is to join them "on" some column. SELECT customers.name FROM customers LEFT JOIN orders ON customers.id = orders.customerid AND orders.id IS NULL The joint table is filled with NULL for those costumers who have not placed an order yet. It is also known as a left outer join.

table example Table ATable B A1A2B1B2B Left outer join by A2 and B3 is A1A2B1B2B

aliases You can use AS to create aliases. If you want to find out which customers live in the same city as another customer select c1.name, c2.name, c1.city FROM customers AS c1, customers AS c2 WHERE c1.city = c2.city AND c1.name != c2.name

utility function from php.net function mysql_fetch_all($query) { if($err=mysql_error()) { return $err;} if(mysql_num_rows($r)) { while($row=mysql_fetch_array($r)) {$result[]=$row; } return $result;}} // usage if(is_array($rows=mysql_fetch_all($query)) { // do something } else { if (! is_null($rows)) { die("Query failed!");} }