You are on page 1of 31

Week010

PHP with Advanced MYSQL


Objectives

• At the end of the module the student is expected to:


• Understand the different concepts of php and mysql statements
• Using date functions
• Creating queries
• Creating concatenated strings
• Using arithmetic operations
• Creating queries with text functions, using aggregates, filtering
PHP 5 Date and Time
The PHP date() function is used to format a date and/or a time.

The PHP Date() Function


The PHP date() function formats a timestamp to a more readable
date and time.

Syntax
date(format,timestamp)
PHP 5 Date and Time

Get a Simple Date

The required format parameter of the date() function specifies how to format the date (or
time).
Here are some characters that are commonly used for dates:
d - Represents the day of the month (01 to 31)
m - Represents a month (01 to 12)
Y - Represents a year (in four digits)
l (lowercase 'L') - Represents the day of the week

Other characters, like"/", ".", or "-" can also be inserted between the characters to add
additional formatting.
The example below formats today's date
in three different ways:
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Output:
Today is 2016/09/16
Today is 2016.09.16
Today is 2016-09-16
Today is Friday
Get a Simple Time
Here are some characters that are commonly used for times:
• h - 12-hour format of an hour with leading zeros (01 to 12)
• i - Minutes with leading zeros (00 to 59)
• s - Seconds with leading zeros (00 to 59)
• a - Lowercase Ante meridiem and Post meridiem (am or pm)

The example below outputs the current time in the specified format:
• <?php
echo "The time is " . date("h:i:sa");
?>

Output:
• The time is 02:09:58am
Get Your Time Zone

• If the time you got back from the code is not the right time, it's probably
because your server is in another country or set up for a different
timezone. So, if you need the time to be correct according to a specific
location, you can set a timezone to use.
• The example below sets the timezone to "America/New_York", then
outputs the current time in the specified format:
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
Output:
The time is 02:10:40am
Create a Date With PHP mktime()

• The optional timestamp parameter in the date() function specifies a


timestamp. If you do not specify a timestamp, the current date and time
will be used (as shown in the examples above).
• The mktime() function returns the Unix timestamp for a date. The Unix
timestamp contains the number of seconds between the Unix Epoch
(January 1 1970 00:00:00 GMT) and the time specified.
Syntax
mktime(hour,minute,second,month,day,year)
<?php
$d=mktime(2, 12, 54, 9, 16, 2016);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
Output:
• Created date is 2016-16-9 2:12:54am
Create a Date From a String With PHP
strtotime()
The PHP strtotime() function is used to convert a human readable string
to a Unix time.
Syntax
strtotime(time,now)
<?php
$d=strtotime("2:13pm April 16 2016");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
Created date is 2016-04-16 2:13:00pm
MySQL INDEXES

• A database index is a data structure that improves the speed of


operations in a table. Indexes can be created using one or more
columns, providing the basis for both rapid random lookups and
efficient ordering of access to records.
• While creating index, it should be considered that what are the
columns which will be used to make SQL queries and create one or
more indexes on those columns.
• Practically, indexes are also type of tables, which keep primary key or
index field and a pointer to each record into the actual table.
Simple and Unique Index:
• You can create a unique index on a table. A unique index means that two
rows cannot have the same index value. Here is the syntax to create an
Index on a table

• CREATE UNIQUE INDEX index_name


• ON table_name ( column1, column2,...);

• You can use one or more columns to create an index. For example, we
can create an index on tutorials_tbl using tutorial_author.

• CREATE UNIQUE INDEX AUTHOR_INDEX


• ON tutorials_tbl (tutorial_author)
Creating Calculated Fields
Concatenating Fields
SQL Statement Result Analysis

SELECT Concat() concatenates strings,


Concat(vend_name, ' (', appending them to each other to
vend_country, ')') create one bigger string. Concat()
FROM vendors requires one or more values to be
ORDER BY vend_name; specified, each separated by
commas.
Concatenating Fields using RTRIM()
SQL Statement Result Analysis

SELECT The RTrim() function trims all


Concat(RTrim(vend_name spaces from the right of a value.
), ' (', By using RTrim(), the individual
RTrim(vend_country), ')') columns are all trimmed properly.
FROM vendors
ORDER BY vend_name;
Using Aliases
SQL Statement Result Analysis
The SELECT statement itself is the
SELECT same as the one used in the
Concat(RTrim(vend_name), ' (', previous code snippet, except that
here the calculated field is followed
RTrim(vend_country), ')') AS
by the text AS vend_title.
vend_title
FROM vendors This instructs SQL to create a
ORDER BY vend_name; calculated field named vend_title
containing the results of the
specified calculation.

As you can see in the output, the


results are the same as before, but
the column is now named vend_title
and any client application can refer
to this column by name, just as it
would to any actual table column.
Performing Mathematical Calculations
SQL Statement Result Analysis
SELECT prod_id,
The expanded_price column
quantity, shown in the previous output is
a calculated field; the calculation
item_price, is simply quantity*item_price.
The client application can now
quantity*item_pri use this new calculated column
ce AS expanded_price just as it would any other
FROM orderitems column.
WHERE order_num =
20005;
MySQL Mathematical Operators
Text Manipulation Functions
SQL Statement Result Analysis
SELECT vend_name, As you can see, Upper()
UPPER(vend_name) AS converts text to uppercase and
vend_name_upcase so in this example each vendor
FROM vendors is listed twice, first exactly as
ORDER BY vend_name; stored in the vendors table, and
then converted to uppercase as
column vend_name_upcase.
Commonly Used Text-Manipulation
Functions
Date and Time Manipulation Functions
Commonly Used Numeric Manipulation
Functions
Summarizing Data
Using Aggregate Functions
Using Aggregate Functions
Function SQL Statement Result
AVG() Function SELECT AVG(prod_price) AS avg_price
FROM products;

COUNT() Function SELECT COUNT(*) AS num_cust


FROM customers;

MAX() Function SELECT MAX(prod_price) AS max_price


FROM products;

MIN() Function SELECT MIN(prod_price) AS min_price


FROM products;

SUM() Function SELECT SUM(quantity) AS items_ordered


FROM orderitems
WHERE order_num = 20005;
Combining Aggregate Functions
SQL Statement Result Analysis
SELECT COUNT(*) AS Here a single SELECT
num_items,MIN(prod_pric statement performs four
e) AS price_min, aggregate calculations in one
MAX(prod_price) AS step and returns four values (the
price_max, number of items in the products
AVG(prod_price) AS table; and the highest, lowest,
price_avg and average product prices)
FROM products;
Grouping Data
SQL Statement Result Analysis
SELECT vend_id, The above SELECT statement specifies
two columns, vend_id, which contains the
COUNT(*) AS num_prods ID of a product's vendor, and num_prods,
FROM products which is a calculated field (created using
GROUP BY vend_id the COUNT(*) function).

The GROUP BY clause instructs MySQL


to sort the data and group it by vend_id.
This causes num_prods to be calculated
once per vend_id rather than once for the
entire table.

As you can see in the output, vendor


1001 has 3 products listed, vendor 1002
has 2 products listed, vendor 1003 has 7
products listed, and vendor 1005 has 2
products listed.
Filtering Groups
SQL Statement Result Analysis

SELECT cust_id, COUNT(*) The first three lines of this SELECT


AS orders statement are similar to the
FROM orders statements seen previously. The final
GROUP BY cust_id line adds a HAVING clause that filters
HAVING COUNT(*) >= 2; on those groups with a COUNT(*) >=
2two or more orders.
Working with Subqueries
SQL Statement Result Analysis

SELECT cust_id Subqueries are always processed


FROM orders starting with the innermost SELECT
WHERE order_num IN statement and working outward.
(SELECT order_num
When the preceding SELECT
FROM orderitems statement is processed, MySQL
actually performs two operations.
WHERE prod_id = 'TNT2');
First it runs the subquery
SELECT order_num FROM
orderitems WHERE prod_id='TNT2'

That query returns the two order


numbers 20005 and 20007.
Working with Subqueries
SQL Statement Result Analysis

SELECT cust_name, To execute this SELECT statement,


cust_contact MySQL had to actually perform three
FROM customers SELECT statements.
WHERE cust_id IN
(SELECT cust_id The innermost subquery returned a
FROM orders list of order numbers that were then
WHERE order_num IN used as the WHERE clause for the
(SELECT order_num subquery above it.
FROM orderitems
WHERE prod_id = 'TNT2')); That subquery returned a list of
customer IDs that were used as the
WHERE clause for the top-level
query. The top-level query actually
returned the desired data.
Joining Tables
SQL Statement Result Analysis

SELECT vend_name, The SELECT statement starts in


prod_name, prod_price, the same way as all the
vendors.vend_id, statements you've looked at
products.vend_id thus far, by specifying the
FROM vendors, products columns to be retrieved. The big
WHERE vendors.vend_id difference here is that two of the
= products.vend_id specified columns (prod_name
ORDER BY vend_name, and prod_price) are in one table,
prod_name; whereas the other (vend_name)
is in another table.
Inner Joins
SQL Statement Result Analysis

SELECT vend_name, The SELECT in the statement is


prod_name, the same as the preceding
prod_price, SELECT statement, but the
vendors.vend_id, FROM clause is different. Here
products.vend_id the relationship between the two
FROM vendors INNER tables is part of the FROM
JOIN products clause specified as INNER
ON vendors.vend_id = JOIN. When using this syntax
products.vend_id; the join condition is specified
; using the special ON clause
instead of a WHERE clause.
The actual condition passed to
ON is the same as would be
passed to WHERE.
Joining Multiple Tables
SQL Statement Result Analysis

SELECT prod_name, This example displays the items in order


vend_name, prod_price, number 20005. Order items are stored in
quantity, products.vend_id, the orderitems table.
vendors.vend_id,
order_num Each product is stored by its product ID,
FROM orderitems, products, which refers to a product in the products
vendors table. The products are linked to the
WHERE products.vend_id = appropriate vendor in the vendors table
vendors.vend_id by the vendor ID, which is stored with
AND orderitems.prod_id = each product record.
products.prod_id
AND order_num = 20005 The FROM clause here lists the three
tables, and the WHERE clause defines
both of those join conditions. An additional
WHERE condition is then used to filter
just the items for order 20005.
SQL PROBLEMS:
• Problem 1. Show the average position that an author appears on a
book if the author has written more than one book. You may list the
author using the ssn column.
• Problem 2. List the number of books that have the same publisher id
and price where the price is known
• Problem 3. Display a list of the authors by the city they live in as long
as they don't live in Maryland or Illinois sort the list by last name within
city. . (Use a subquery)
• Problem 4. Show a list of all authors and the books they have written.
Except don't show any authors whose last name has the letter 'a' or 'o'
in it.
• Problem 5. List the authors (using their last and first names) who have
written books published by the publisher whose name begins with 'Bin'.

You might also like