Mysql 4
Mysql 4
U.KUMARASWAMY MCA.
For example, if you want to find records in the grocery_inventory table where the (irst ina
of the item starts with the letter A, you would use the following:
name LIKE
item
WHERE
SELECT * FROM grocery inventory
ICurr_qty |
| id | item name item desc | item _price
+
0.25 | 1000
| 1 | Apples | Beautiful, ripe apples.
+
tables: fruitfrom
Suppose that you have twoSelecting
Multiple Tables
and color. You can select all rows from each of the
two tables
When youbywant
using two separate
to select SELECT
rom both tables statements.
at once, the syntax of the SELECT statement differs
somewhat. First, you must ensure that all the tables you're usng n your query appear in the
LECT statement. Using the fruit and color example. if you simply
FROM
want to clause of the
select all SELI and rows from both tables, you might think you
columns would use the
following SELECT statement: fruit, color;
SELECT * FROM
id | colorname |
| id | fruitname
+.
1 | apple 1 | red |
1 | red |
orange
1 ced
| 3 | grape
4 banana 1|red
1 apple |2 orange
orange 2 | orange
3 grape 2 | orange
4 | banana 2 | orange
1 | apple purple
2 | orange 3 | purple
3 grape purplo
4 | banana 3 purple
1 | apple 4 yellow
| orange 4 | yellow
| 3 grape 4 yellow
4 | banana | 4 | yellow
Sixteen rows of repeated information are probably not what you were looking for. What this
query did is literally join a row in the color table to each row in the fruit table. Because there
are 4 recordsin the fruit table and 4 entries in the color table, thae's 16 records returned to
you.
When you select from multiple tables, you must build proper WHERE clauses to ensure that
youreally get what you want. In the case of the fruit and color tables, what you really want
is to see the fruitname and colorname records from these two tables where the IDs of each
match up.
Simply, you append the table name to the field name, like this:
tablename.fieldname
So, the query for selecting fruitname and colorname from both tables where the IDs match
wOuld be as follows:
SELECT fruitname, colorname FROM fruit, color WHERE fruit.id =
This query produces a better result for you: color.id;
Programming with PHP and MySQL For BSC VÊh Sem Page| 76
VYSHNAVI DEGREE COLLEGE, YMG.
U . K U M A R AS W A M YMCA.
fruitname colorname
| apple |red
orange | orange
| grape I purple
banana | yelloN
4
U s i n gJ O I N
several types of
JOINs in MySQL, all of which refer to the order in which the
You
can
use
together
and the results are displayed. The type of JOIN used with the fruit
are put
tables
| apple | red
| orange | orange
grape | purple
| banana | yellow
4 rows in set (0.00 sec)
Using Subqueries
SQL statement.
statement that appears within another
Simply stated, a subquery is a SELECT for bulky
prove extremely useful because they often eliminate the need
Such queries can elíminate the need
queries, and in the case of application programming, subqueries can
JOIN
for multiple queries within loops.
syntax is shown here:
An example of the basic subquerycolumns FROM table name WHERE somecolumn
=
expressions and
SELECT
(SUBQUERY) ;
as shown here:
UPDATE and DELETE statements, (SUBOUERY) ;
Youcan also use subqueries with =
DELETE FROM table
name WHERE somecolumn
WHERE somecolumn =
= 'something'
somecolumn
UPDATE table name
SET
(SUBQUERY) ;
in parentheses-no exceptions!
The subquery must always appear
Page | 77
PHP and MySQL For BSC
VÊh Sem
Programming with
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE COLLEGE,
The following example uses a subauery to obtain records from users 1n te adster
table who have an email address in the cmail table:
name
name
SELECT £irstname, lastname FROM master
email) ;
FROM
WHERE name id IN (SELECT name id
1 | apple
| ripe
rotten
2 | orange
| ripe
3 | grape
| rotten
4 | banana
(0.00 sec)
4 rows in set
To update the status of the fruit to ripe, useSET status
'ripe';
UPDATE f r u i t 'grape' i
fruit name
UPDATE fruit SET names will be
set to 'grape'.You
'ripe'and all fruit
But abOve commands all fruits status set. as table, unless you reallyintend to
when updating8 a
must be careful and use a condition
records to the same value.
change all the columns for all
fruit name | status
| id |
|ripe
1 grape
| ripe
2 grape
3 | grape | ripe
4 | grape | ripe
(0.00 sec)
4 rows in set
| 1 apple ripe
2 pear ripe
3 | banana | ripe
4 | grape | ripe
4 rows in set (0.00 sec)
Another
similar to the
INSERT command.
remarkably
INTO table name (column list) VALUES (colunn values) ;
works like this: If the record you are inserting into the table
R E P L A C E
statement
the record in the
that matches a record alreadyin the table,
REPLACE
means you
are using
Page | 79
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE.COLLEGE,
| 1 |apple ripe
| 3 | banana ripe
+-
2 rows in set (0.00 sec)
To remove the oldest record, first use ORDER BY to sort the results appropriately, and then
use LIMIT to remove just one record:
DETEE FROM access log ORDER BY date accessed DESC LIMIT 1;
| LENGTH(This is cool|') |
13 |
- -+
1 row in set (0.00 sec)
The fun begins with the CONCAT) function, which concatenates two or more strings:
SELECT CONCAT ('My', 'S', QL');
This query results in the following:
also
use concat () function on any table.
We
can
WS) stands for concatenate with separator. The separator can be anything you
uses whitespace:
CONTACT_W
SELECT
CONCAT WS (
and | Padding Functions:
Trimming
provides several
functions for adding and removing extra characters (including
MySQL
from strings. The RTRIM) and
LTRIMO functions remove whitespace from
whitespace)
left, side of astring:
either theright or SELECT RTRIM('stringstring '):
results inthe following, although it is difficult to se the change:
This query +
| RTRIM('stringstring ")|
| stringstring
+
| LTRIM(' stringstring') +|
| stringstring
+
sec)
1 row in set (0.00
leading Xcharacters from the
For example, to remove the
string XXXneedleXXX, use FROM
'XXXneedleXXX') ;
SELECT TRIM (LEADING 'X
needleXXX
+
sec)
1 row in set (0.00 from the end of the
string:
remove the characters
to
You can use TRAILING TRIM(TRAILING
'XXXneedleXXX');
X FROM
SELECT
are as follows:
The results of this query
Page |81
MySQL For BSC V[h Sem
Programming with PHP and
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE
+
COLLEGE, VNMG.
I IRIM(TRAILING'X FROM 'XXXneedleXXX') |
+
| XXXneedle
'XXXneedleXXX') |
T TRIM('X FROM - -+
|needle
| needleXXXX
1 row in set (0.00 sec)
Location and Position Functions:
The group of location and position functions is useful for finding parts of strings within
other strings. The LOCATE)function returns the position of the first occurrence of a given
substring within the target string. For example,'haystackneedlehaystack');
SELECT LOCATE('needle'
you can look for anedle in ahaystack:
You should see this result:
+
| LOCATE('needle', 'haystackneedlehaystack') |
+
9|
Programming with PHP and MySQL For BSc V[h Sem Page | 82
U.KUMARASWAMYMCA. VYSHNAVI DEGREE COLLEGE, YMG.
looking
for needle in haystack before position 9, you'll receive a result.
needle. starts at position 9, youll receive a0result if you
O h e r w i s e , because,
you
slart
specify a greater
Il
slarting
position.
SubstringFunctions:
Ilyourgoal is to extract a substring from a target string, several functions fit the bill. Given a
starting
position,
and length, you can use the SUBSTRING( ) function. This example
string,
characters from the string MySQL, starting at position 2:
gets
t h r e e
resultis
as
The
| SUBSTRING("MySQL", 2, 3) |
|y$Q
1 row in set (0.00 sec)
want a few characters from the left or right ends of a string, use the
If youjust functions:
LEFT) and RIGHT()
SELECT LEFT ("MySQL", 2) ;
The result of this query is as follows:
| LEFT("My SQL", 2) |
| My
+
|RIGHT("MySQL", 3) |
SQL
Programming with PHP and MySQL For BSc VIh Sem Page | 83
U.KUMARA SWAMY MCA.
VYSHNAVI DEGREE
COLLEGE,,YMG.
| LCASE(MYSQL') |
-+
| mysql
+ -+
| bowwowbowwowbowwowbowwOw |
+ +
DAYOFWEEK (date)
S y n t a x :
Example-
SELECT DAYOEWEEK ('2012-01-09'):
T h i sq u e r y
produces the following result:
DAYOFWEEK(2012-01-09') |
|2|
sec)
in set (0.00
1row
Ther e s u l ts h o w s
sthat January 9, 2012, was weekday index 2, or
The WEEKDAY) function returns the weekday index for adateMonday.
value (a number from 0to).
Note: 0= Monday, 1= Tuesday, 2=Wednesday,3= Thursday, 4= Friday, 5 =
Saturday, 6= Sunday.
Syntax - WEEKDAY(date)
SELECT WEEKDAY(2012-01-09");
| WEEKDAY(2012-01-09") |
|0|
+
| DAYOFMONTH(2012-01-09) |
|9|
DAYOFYEAR(2012-01-09") |
|09
Programming with PHP and MySQL For BSc V[h Sem Page | 85
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE
COLLEGE
orders with a field the order was placed, we can quickly get a
E,YMG.
containing
the orders placed on any the date
orders were counl of
the first half of the month given day of the week, or see how many
versus the
placed during,
The following two queries show second hal. orders were placed during the first three
the week (throughout all months) how many the remaining days of the
week: days of
and then <4;
SELECT COUNT(id) FROM orders WHERE
DAYOFWEEK(date_ordered)
>3;
SELECT COUNT(id) FROM orders WHERE
DAYOFWEEK(date_ordered)
WHERE ) >15;
SELECT
DAYOFMONTH(date_ordered)
COUNT(id)
we can use FROM orders
the DAYNAMEO s WHERE
function to add nore life to your results because it returns the
| DAYNAME(date_ordered) |
Thursday |
Monday |
Thursday
Thursday |
Wednesday |
Thursday |
Sunday |
Sunday |
8 rows in set (0.00 sec)
Functions aren't limited to WHERE clauses- we can use them in OkDEK BI
clauses as well, such as the following:
orders ORDER BY
SELECT DAYNAME(date ordered) FROM
DAYOFWEEK(date_ordered):
parts of the calendar, and
Working with Months and Years Davs of the week are not the only
well. Just like the DAYOFWEEK)
MysQL has functions specifically for months and years as
MONTHNAME) return the number of the
and DAYNAME) functions, MONTH) and
example:
month in ayear and the name of the month for a given date. For
SELECT MONTH(2012-01-09), MONTHNAME(2012-01-09");
This query produces the following:
|MONTH(2012-01-09') | MONTHNAME(2012-01-09) |
+
|1|January |
+
1row in set (0.00 sec)
a lot of
Using MONTHNAME) on the orders table shows the proper results but can show
repeated data:
+.
|MONTHNAME(date_ordered) |
Programming with PHP and MySQL For BSc VÊh Sem Page |86
U K U M A R AS W A M YMCA. VYSHNAVI DEGREE COLLEGE, YMG.
/ 2011
/ 2012
sec)
set(0.00
1rowin
Working with Weeks:
DAYNAME)RReturns the name of the week day of adate specified in the argument.
Syntax - DAYNAME(date1)
GELECT DAYNAME(2001-12-30');
Here's proof:
+
|DAYNAME('2001-12-30) |
| Sunday |
1row in set (0.00 sec)
WEEK) returns the week number for agiven date.
Syntax :- WEEK(date[,mode]):
Working with Hours, Minutes, and Seconds:
HOUR) -Returns the HOUR of atime. The return value is within the range of 0to 23
for time-of-day values. The range of time values may be larger than 23.
Syntax - HOUR(ime)
MINUTE) - returns a MINUTE from a time or datetime value.
Syntax: MINUTE(imel);
SECOND)- Returns the second for atime. The return value is in the range of 0to 59.
Syntax: SECOND(tm)
SELECT HOUR(2012-01-09 07:27:49) AS hour,
MINUTE(2012-01-09 07:27:49) AS minute,
SECOND(2012-01-09 07:27:49") AS second;
This query produces the following:
t
| hour | minute | second |
|7|27 | 49 |
t-+ -+
Thae's a lot of queries to get at one time from a datetime field-we can put the
Programming with PHP and MySQL For BSc VÊth Sem Page |87
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE
COLLEGE, YMG.
hour and minute together and even use CONCAT_WS)to put the: between the
results and get a representation of the time:
SELECT CcONCAT_WwS(:",HOUR(2012-01-09 07:27:49"),
MINUTE(2012-01-09 07:27:49))AS sample_time;
This query produces the following:
|sample_time |
+
| 7:27 |
+
Programming with PHP and MySQL For BSC V[h Sem Page | 88
U.KUMARASWAMYMCA. VYSHNAVI DEGREE COLLEGE, YMG.
T A B L E1 6 . 2
Continued
Hour (0 through 23)
k Hour, padded digits (01
through 12)
Hour (1 through 12)
Minutes, padded d1gits (00
through 59)
Seconds, padded digits (00
through
Seconds, padded digits (00 through 59)
59)
Time, 12-hour clock
(hh:mm:ss [APIM)
Time, 24-hour clock (hh:mm:ss)
AM or PM
Todisplay the 02:02 result that we rigged in the previous section, you use the %h
and %i options to return the hour and minute from the date with a: between the
two
options. For example:
SELECT DATE FORMAT(2012-01-09 02:02:00', "%h:%i) AS sample_time;
This query produces the following:
| sample_time |
+.
|02:02 |
Programming with PHP and MySQL For BSc VIà Sem Page 89
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE
1. Issue the BEGIN Command to begin a new transaction. COLLEGE, VMG.
2. Select avalue from tablel to insert into table2.
3. If a value cannot be selected from tablel, issue a ROLLBACK command to
transaction ends and that the tables return to their previous state. ensure ththal the
4. If a value can be selected from tablel, insert a value into table2.
5. If the insertion of a record into table2 fails, issue a ROLLBACK command to ensure that
the transaction ends and that the tables return to their previous state.
6. Ifa value can be inserted into tablel, insert a value into table2.
7. If the insertion of a record into table3 fails, issue a ROLLBACK command
the transaction ends and that the tables return to their to ensure that
previous state.
8. However, if the insertion of arecord into table3 is successful,
issue a COMMIT
toensure that the transaction ends and that the tables update
appropriately. Command
Stored procedure
a stored procedure is a procedure in SQL that is stored in the database server rather
web server. than the
. Better performance-Stored procedures exist as precompiled SQL in the
database, so a
typical two-step process (compile and execute) becomes a single-step process (execute).
Ease of maintenance- Maintaining One statement in one place (the
database) is
significantly less time-consuming than maintaining one statement in numerous places, such
as all through scripts on your web server.
The syntax for creating a basic stored procedure is as follows:
CREATE PROCEDURE procedure_name () query /7
CREATE PROCEDURE spl 0 SELEcT * FROM emp where deptno=10;
To call the stored procedure, use the CALL command:
CALL sp1 () ;
Above CALL query displays all the details of employees working in department number 10.
Connecting to MySQL with PHP
To successfully use the PHP functions to talk to MySQL, you must have MySQL running at a
location to which your web server can connect (not necessarily the same machne as yor
web server). You also must havecreated a user (witha password), and you must know the
name of the database to which you want to connect.
Making a Connection:
The basic syntax for a connection to MySQL 0s as follows:
Fmysqli = nysqli connect ("hostname", "username", "password",
"database") i
The value of $mnysgli is the result of the function and is used in later furnctions for
communicating with MySQL.
With sanmple values inserted, the connection code looks like this:
Smysqli = mysqli_connect ("localhost", "joeuser", "somepas s",
"testDB") ;
is a working example of a connection script. It creates a new connection in line 2 and then
tests to see whether an error occurred. If an error occurred, line 5 prints an error mnessage and
uses the mysqli connect_error(0 function to print the message. If no error occurs, line 8prints
Programming with PHP and MySQL For BSc VIjh Sem Page | 90
VYSHNAVIDEGREE COLLEGE, YMG.
UKUMARASWAMYMCA.
includes
hostinformation resulting from calling the mysqli get host_info)
that
message
a
function. mysqli( ("localhost", "joeuser", "somepass , "testDB*);
< p h p
= new
Smysqli
1:
2: (mysqli
Connect errno(0)
3:
printf( "Connect failed: %s\n", mysqli connect error0);
if
4:
exit();
5:
6 ) else {
printf("Host information: %s\n". mysqli get host info(Smy sqli) );
7
8.
9: }
10: ?>
this script as mysqlconnect.php and place it in the document area of your web server.
t h es scriptt with your web browser and you willsee something like the following, if the
Save
Access
connection was successful.
Programming with PHP and MySQL For BSc V[h Sem Page 91
U.KUMARA SWAMY MCA.
VYSHNAVI DEGREE E
Retrieving Error Messages: COLLEGE, YMG.
Take some time to familiarize yourself with the mysqli_error() function; it
friend. When used in conjunction with the PHP die() function, will become
which
at the point at which it appears, the mysqli error)funcion returns a simply
helpful
exits the your
when youmake a mistake. error m script
messag
Working with MySQL Data
Inserting, updating, deleting, and retrieving data all revolve around the use
mysqli query) function to execute the basic SQL queries you learned about
"Learning Basic SQL Commands." For INSERT, UPDATE, and DELETEin Chapter 16,
of the
additional scripting is required after the query has been executed because queries, no
displaying any results (unless you want to). When using SELECT queries, you're no
you have
a few
options for displaying the data retrieved by your query.
Inserting Data with PHP:
The easiest (and safest) method for inserting data at this stage in the game is to
simply hard-code the INSERT statement, as shown in
1: <7php
2: Surysqli = ysqli_ connect(" localhost', 'joeuser", "somepass, 'testD8'):
4:
if (ysqli_connect errno (0) {
printf("Connect failed: As\n', mysqli_ connect_error());
6: exit ();
7: } else {
8: $sql = INSERT INTO testTable (testField) VALUES ('some value'):
9: ^res = mysqli_query (Smy sqli, $sql);
10:
11: if (Sres == TRUE) {
12: echo "A record has been inserted.':
13: }else {
14: print ("Could not insert record: %s\n, mysqli error ($mysqli));
15:
16:
17: aysqli close (S=ysqli) ;
18:
19: >
Programming with PHP and MySQL For BSc VIth Sem Page | 92
U.KUMARASWAMY MCA.
VYSHNAVI DEGREE COLLEGE, YMG,
in a
unified view.
inlormaltion
table and field names to use
for your online address book.
shows sample
Table
20.1.
In a information
atthis
look
fields: should be primary or unique keys
ofthe TABLE 20.1 Address Book Table and Field Names
Table Name Field Names
master name id, date added, date modified, f name, 1_name
address id, master_id, date added, date modified, address. city.
state, zipcode, type
telephone id, master_id, date added, datemodified, tel_number,
type
fax id, master id, date added, date modified, fax_number.
type
email id, master id, date added, date modified, email, type
personal notes id, master id, date added, date modified, note
The following SQL statement creates the master name table:
CREATE TABLE master name (
id INT NOT NULL PRIMARY KEY AUTO INCREMENT,
date added DATETIME,
date modified DATETIME,
f name VARCHAR (75),
1 name VARCHAR (75)
The telephone, fax, and email tables are all variations on the same
theme :
CREATE TABLE telephone (
id INT NOT NULL PRIMARY KEY AUTO INCREMENT,
master id INT NOT NULL,
date added DATETIME,
date modified DATETIME,
Programming with PHP and MySQL For BSc VIh Sem Page 93
VYSHNAVI DEGREE COLLEGE,NMG,
U.KUMARA SWAMY MCA.
Programming with PHP and MySQL For BSC VIh Sem Page 94
VYSHNAVI DEGREE COLLEGE, YMG.
U.KUMARASWAMY MCA.
C Ohep/locahort
My Address Book
sMmpoeat
because you'll poterntially l be adding information to six different tables doesn't mean
Just will be monstrous.
your
form or script
OAdd an intry
c ohrp/ocahos/ 23j 03entry pro K
Add an Entry
S t A1dh;
-AMro
-Teplcne Nuatet
-FSb
Viewing Records
If you verified your work in the preceding section by issuing queries through the
MySQL monitor or other interface, you probably became tired of typing SELECT *
FROM...for every table.
Select an Entry
Seedt a Recat
Doa. lana
-Saled Ong
Atla. Anne
Smth Jctn
Programming with PHP and MySQL For BSc VIh Sem Page | 95
U.KUMARA SWAMY MCA. VYSHNAVI DEGREE COLLEGE,.VMG.
Record(s) Deleted
odd1oo eto dekte ancthr7