You are on page 1of 80

Module-V

MySQL and PHP with MySQL


Dr. Mareeswari. V
Assistant Professor(Sr)
School of Information Technology and Engineering
VIT University, Vellore.

1 Dr.Mareeswari V/SITE/VIT University/ Vellore


Introduction
 SQL is a standard language for accessing databases.
 SQL is used to access and manipulate data in: MySQL, SQL
Server, Access, Oracle, Sybase, DB2, and other database
systems.

2 Dr.Mareeswari V/SITE/VIT University/ Vellore


MySQL
 It is a database system used on the web
 It is a database system that runs on a server
 It is ideal for both small and large applications
 It is very fast, reliable, and easy to use
 It supports standard SQL
 It compiles on a number of platforms
 It is free to download and use
 It is developed, distributed, and supported by Oracle Corporation
 MySQL is the most popular database system used with PHP.
 Eg : Friendster,Yahoo, and Google
 In 1996 T.c.X. DataKonsultAB , a consulting firm in Sweden developed
MySQL.
3 Dr.Mareeswari V/SITE/VIT University/ Vellore
Advantages & Disadvantages

Advantages:
 very fast
 reliable and easy to use
 multi-threaded multi-user and robust SQL database server.
Disadvantages:

 Missing Sub-selects.
 MySQL doesn't yet support the Oracle SQL extension: SELECT
... INTO TABLE , but supports INSERT INTO ... SELECT ..
 Does not support Stored Procedures and Triggers.
 MySQL doesn't support views, but this is on the TODO.

4 Dr.Mareeswari V/SITE/VIT University/ Vellore


How It Works
MySQL is based on a client/server model

5 Dr.Mareeswari V/SITE/VIT University/ Vellore


Types of Commands
Data Definition Language (DDL)
Commands that define a database, including creating, altering, and
dropping tables and establishing constraints.

Data Manipulation Language (DML)


Commands that send query to a database like add new records, delete
records, update the records and select the records.

Data Control Language (DCL)


Commands that control a database, including administering privileges
and committing data.

6 Dr.Mareeswari V/SITE/VIT University/ Vellore


MySQL Commands
Data Definition Language (DDL):
 Create  Drop
 Alter
Data Manipulation Language (DML):
 Select  Update
 Insert  Delete
Data Control Language (DCL):
 Commit  Revoke

7 Dr.Mareeswari V/SITE/VIT University/ Vellore


Database process
 CREATE DATABASE databaseName;
 DROP DATABASE databaseName;
 SHOW DATABASES;
 USE databaseName;
DDL processs:
 SHOW TABLES;
 DESCRIBE table;
 CREATE TABLE tableName(name1 type1, name2 type2, ...);
 ALTER TABLE tableName add/modify fieldname type,……;
 DROP TABLE tableName;
DML Process:
 INSERT INTO TABLE nameVALUES( value1, value2, ...);
 SELECT field1, field2, ... FROM tableName;
 UPDATE tablename SET field = exp/val [where condition];
 DELETE FROM tablename [where condition];
8
Dr.Mareeswari V/SITE/VIT University/ Vellore
Datatype – Text

9 Dr.Mareeswari V/SITE/VIT University/ Vellore


Datatype -Number

10 Dr.Mareeswari V/SITE/VIT University/ Vellore


Datatype - Date

11 Dr.Mareeswari V/SITE/VIT University/ Vellore


In XAMPP
 After installation (Don’t install in C drive)
F:/xampp/xampp-control.exe  right click(Run as administrator)
To start Apache in XAMPP
If it is error it Start, then F:/xampp/apache_start.bat  right click(Run as administrator)
Check it on any browser like http://localhost:8088 (port number
varied on setting)
F:/xampp/htdocs to store all html,css, php files
 Now run your PHP program in browser
 http://localhost:8088/first.php
 To start MySQL in XAMPP
 Click Shell to get command window

12 Dr.Mareeswari V/SITE/VIT University/ Vellore


In xamppstart MySQL click shell

13 Dr.Mareeswari V/SITE/VIT University/ Vellore


Database creation

14 Dr.Mareeswari V/SITE/VIT University/ Vellore


My SQL – Start Client
 Without using passwords
(when the password for the specified user is empty

mysql -u <user> -p <pwd> -h <Host>

 Using passwords mysql -u


<user> -h <Host> -p Example:
mysql -u root -h localhost
 Exiting with the command quit or exit.

15 Dr.Mareeswari V/SITE/VIT University/ Vellore


16 Dr.Mareeswari V/SITE/VIT University/ Vellore
Sample Session
 For example:

Enter password: *****


Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 241 to server version: 3.23.49

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

 To exit the MySQL Shell, just type QUIT or EXIT:

mysql> QUIT
mysql> exit

Dr.Mareeswari V/SITE/VIT University/ Vellore 17


Basic Queries
 Once logged in, you can try some simple queries.
 For example:

 Note that most MySQL commands end with a semicolon (;)


 MySQL returns the total number of rows found, and the total time to execute
the query.

Dr.Mareeswari V/SITE/VIT University/ Vellore 18


Online compiler

19 Dr.Mareeswari V/SITE/VIT University/ Vellore


Basic Queries
 Keywords may be entered in any lettercase.
 The following queries are equivalent:

mysql> SELECT VERSION(), CURRENT_DATE;


mysql> select version(), current_date;
mysql> SeLeCt vErSiOn(), current_DATE;

Dr.Mareeswari V/SITE/VIT University/ Vellore 20


Basic Queries
 Here's another query. It demonstrates that you can use
mysql as a simple calculator:

mysql> SELECT SIN(PI()/4), (4+1)*5;


+-------------+---------+
| SIN(PI()/4) | (4+1)*5 |
+-------------+---------+
| 0.707107 | 25 |
+-------------+---------+

Dr.Mareeswari V/SITE/VIT University/ Vellore 21


Basic Queries
 You can also enter multiple statements on a single line. Just end
each one with a semicolon:

Dr.Mareeswari V/SITE/VIT University/ Vellore 22


Multi-Line Commands
 mysql determines where your statement ends by looking for
the terminating semicolon, not by looking for the end of the
input line.
 Here's a simple multiple-line statement:

Dr.Mareeswari V/SITE/VIT University/ Vellore 23


Canceling a Command
 If you decide you don't want to execute a command that you
are in the process of entering, cancel it by typing \c

mysql> SELECT
-> USER()
-> \c
mysql>

Dr.Mareeswari V/SITE/VIT University/ Vellore 24


Using a Database
 To get started on your own database, first check which databases
currently exist.
 Use the SHOW statement to find out which databases currently exist
on the server:

Dr.Mareeswari V/SITE/VIT University/ Vellore 25


Using a Database
 To create a new database, issue the “create database”
command.
 To the select a database, issue the “use” command.

Dr.Mareeswari V/SITE/VIT University/ Vellore 26


Creating a Table
 Once you have selected a database, you can view all database
tables.
 An empty set indicates that I have not created any tables yet.

Dr.Mareeswari V/SITE/VIT University/ Vellore 27


Creating a Table
 Let’s create a table for storing pets.
 Table: pets
 name: VARCHAR(20)
 owner: VARCHAR(20)
 species: VARCHAR(20)
 sex: CHAR(1)
 birth: DATE
 date: DATE
 petid: INT(3) VARCHAR is
usually used
to store string
data.
Dr.Mareeswari V/SITE/VIT University/ Vellore 28
Creating a Table
 To create a table, use the CREATE TABLE command:

mysql> CREATE TABLE pet (


-> name VARCHAR(20),
-> owner VARCHAR(20),
-> species VARCHAR(20),
-> sex CHAR(1),
-> birth DATE, death DATE);
Query OK, 0 rows affected (0.04 sec)

Dr.Mareeswari V/SITE/VIT University/ Vellore 29


Create table in Phpmyadmin:
Start Apache Click Admin

30 Dr.Mareeswari V/SITE/VIT University/ Vellore


Browser opened, click phpMyAdmin

31
Dr.Mareeswari V/SITE/VIT University/ Vellore
32 Dr.Mareeswari V/SITE/VIT University/ Vellore
Create a new database

33 Dr.Mareeswari V/SITE/VIT University/ Vellore


Create a table

Click Save
button at
bottom

34
Dr.Mareeswari V/SITE/VIT University/ Vellore
35 Dr.Mareeswari V/SITE/VIT University/ Vellore
Insert all values Click Go Button

36 Dr.Mareeswari V/SITE/VIT University/ Vellore


37 Dr.Mareeswari V/SITE/VIT University/ Vellore
Showing Tables
 To verify that the table has been created:
mysql> show tables;
+------------------+
| Tables_in_test |
+------------------+
| pet |
+------------------+
1 row in set (0.01 sec)

Dr.Mareeswari V/SITE/VIT University/ Vellore 38


Describing Tables
 To view a table structure, use the DESCRIBE command:

mysql> describe pet;


+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name | varchar(20) | YES | | NULL | |
| owner | varchar(20) | YES | | NULL | |
| species | varchar(20) | YES | | NULL | |
| sex | char(1) | YES | | NULL | |
| birth | date | YES | | NULL | |
| death | date | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
6 rows in set (0.02 sec)

Dr.Mareeswari V/SITE/VIT University/ Vellore 39


Deleting a Table
 To delete an entire table, use the DROP TABLE command:

mysql> drop table pet;


Query OK, 0 rows affected (0.02 sec)

Dr.Mareeswari V/SITE/VIT University/ Vellore 40


Loading Data
 Use the INSERT statement to enter data into a table.
 For example:

INSERT INTO pet VALUES


('Fluffy','Harold','cat','f',
'1999-02-04',NULL);

Dr.Mareeswari V/SITE/VIT University/ Vellore 41


SQL Select
 The SELECT statement is used to pull information from a
table.
 The general format is:

SELECT what_to_select
FROM which_table
WHERE conditions_to_satisfy

Dr.Mareeswari V/SITE/VIT University/ Vellore 42


Selecting All Data
 The simplest form of SELECT retrieves everything from a table

mysql> select * from pet;


+----------+--------+---------+------+------------+------------+
| name | owner | species | sex | birth | death |
+----------+--------+---------+------+------------+------------+
| Fluffy | Harold | cat | f | 1999-02-04 | NULL |
| Claws | Gwen | cat | f | 1994-03-17 | NULL |
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
| Fang | Benny | dog | m | 1999-08-27 | NULL |
| Bowser | Diane | dog | m | 1998-08-31 | 1995-07-29 |
| Chirpy | Gwen | bird | f | 1998-09-11 | NULL |
| Whistler | Gwen | bird | | 1997-12-09 | NULL |
| Slim | Benny | snake | m | 1996-04-29 | NULL |
+----------+--------+---------+------+------------+------------+
8 rows in set (0.00 sec)

Dr.Mareeswari V/SITE/VIT University/ Vellore 43


Selecting Particular Rows
 You can select only particular rows from your table.
 For example, if you want to verify the change that you
made to Bowser's birth date, select Bowser's record like
this:
mysql> SELECT * FROM pet WHERE name = "Bowser";
+--------+-------+---------+------+------------+------------+
| name | owner | species | sex | birth | death |
+--------+-------+---------+------+------------+------------+
| Bowser | Diane | dog | m | 1998-08-31 | 1995-07-29 |
+--------+-------+---------+------+------------+------------+
1 row in set (0.00 sec)

Dr.Mareeswari V/SITE/VIT University/ Vellore 44


Selecting Particular Rows
 To find all animals born after 1998
SELECT * FROM pet WHERE birth >= "1998-1-1";

 To find all female dogs, use a logical AND


SELECT * FROM pet WHERE species = "dog" AND sex = "f";

 To find all snakes or birds, use a logical OR


SELECT * FROM pet WHERE species = "snake"
OR species = "bird";

Dr.Mareeswari V/SITE/VIT University/ Vellore 45


Selecting Particular Columns
 If you don’t want to see entire rows from your table, just
name the columns in which you are interested, separated by
commas.
 For example, if you want to know when your pets were
born, select the name and birth columns.

Dr.Mareeswari V/SITE/VIT University/ Vellore 46


Selecting Particular Columns
mysql> select name, birth from pet;
+----------+------------+
| name | birth |
+----------+------------+
| Fluffy | 1999-02-04 |
| Claws | 1994-03-17 |
| Buffy | 1989-05-13 |
| Fang | 1999-08-27 |
| Bowser | 1998-08-31 |
| Chirpy | 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim | 1996-04-29 |
+----------+------------+
8 rows in set (0.01 sec)

Dr.Mareeswari V/SITE/VIT University/ Vellore 47


Sorting Data
 To sort a result, use an ORDER BY clause.
 For example, to view animal birthdays, sorted by date:

mysql> SELECT name, birth FROM pet ORDER BY birth;


+----------+------------+
| name | birth |
+----------+------------+
| Buffy | 1989-05-13 |
| Claws | 1994-03-17 |
| Slim | 1996-04-29 |
| Whistler | 1997-12-09 |
| Bowser | 1998-08-31 |
| Chirpy | 1998-09-11 |
| Fluffy | 1999-02-04 |
| Fang | 1999-08-27 |
+----------+------------+
8 rows in set (0.02 sec)
Dr.Mareeswari V/SITE/VIT University/ Vellore 48
Sorting Data
 To sort in reverse order, add the DESC (descending
keyword)

mysql> SELECT name, birth FROM pet ORDER BY birth DESC;


+----------+------------+
| name | birth |
+----------+------------+
| Fang | 1999-08-27 |
| Fluffy | 1999-02-04 |
| Chirpy | 1998-09-11 |
| Bowser | 1998-08-31 |
| Whistler | 1997-12-09 |
| Slim | 1996-04-29 |
| Claws | 1994-03-17 |
| Buffy | 1989-05-13 |
+----------+------------+
8 rows in set (0.02 sec)
Dr.Mareeswari V/SITE/VIT University/ Vellore 49
Working with NULLs
 NULL means missing value or unknown value.
 To test for NULL, you cannot use the arithmetic comparison
operators, such as =, < or <>.
 Rather, you must use the IS NULL and IS NOT NULL
operators instead.

Dr.Mareeswari V/SITE/VIT University/ Vellore 50


Working with NULLs
 For example, to find all your dead pets (what a morbid example!)

mysql> select name from pet where death


>IS NOT NULL;
+--------+
| name |
+--------+
| Bowser |
+--------+
1 row in set (0.01 sec)

Dr.Mareeswari V/SITE/VIT University/ Vellore 51


Pattern Matching
 MySQL provides:
 standard SQL pattern matching; and
 regular expression pattern matching, similar to those used by Unix utilities
such as vi, grep and sed.
 SQL Pattern matching:
 To perform pattern matching, use the LIKE or NOT LIKE comparison
operators
 By default, patterns are case insensitive.
 Special Characters:
 _ Used to match any single character.
 % Used to match an arbitrary number of characters.

Dr.Mareeswari V/SITE/VIT University/ Vellore 52


Pattern Matching Example
 To find names beginning with ‘b’:

mysql> SELECT * FROM pet WHERE name LIKE "b%";


+--------+--------+---------+------+------------+------------+
| name | owner | species | sex | birth | death |
+--------+--------+---------+------+------------+------------+
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 |
+--------+--------+---------+------+------------+------------+

Dr.Mareeswari V/SITE/VIT University/ Vellore 53


Pattern Matching Example
 To find names ending with `fy':

mysql> SELECT * FROM pet WHERE name LIKE "%fy";


+--------+--------+---------+------+------------+-------+
| name | owner | species | sex | birth | death |
+--------+--------+---------+------+------------+-------+
| Fluffy | Harold | cat | f | 1993-02-04 | NULL |
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
+--------+--------+---------+------+------------+-------+

Dr.Mareeswari V/SITE/VIT University/ Vellore 54


Pattern Matching Example
 To find names containing a ‘w’:

mysql> SELECT * FROM pet WHERE name LIKE "%w%";


+----------+-------+---------+------+------------+------------+
| name | owner | species | sex | birth | death |
+----------+-------+---------+------+------------+------------+
| Claws | Gwen | cat | m | 1994-03-17 | NULL |
| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 |
| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL |
+----------+-------+---------+------+------------+------------+

Dr.Mareeswari V/SITE/VIT University/ Vellore 55


Pattern Matching Example
 To find names containing exactly five characters, use the _ pattern character:

mysql> SELECT * FROM pet WHERE name LIKE "_____";


+-------+--------+---------+------+------------+-------+
| name | owner | species | sex | birth | death |
+-------+--------+---------+------+------------+-------+
| Claws | Gwen | cat | m | 1994-03-17 | NULL |
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
+-------+--------+---------+------+------------+-------+

Dr.Mareeswari V/SITE/VIT University/ Vellore 56


Regular Expression Matching
 The other type of pattern matching provided by MySQL uses
extended regular expressions.
 When you test for a match for this type of pattern, use the
REGEXP and NOT REGEXP operators (or RLIKE and NOT
RLIKE, which are synonyms).

Dr.Mareeswari V/SITE/VIT University/ Vellore 57


Regular Expressions
 Some characteristics of extended regular expressions are:
 . matches any single character.
 A character class [...] matches any character within the
brackets. For example, [abc] matches a, b, or c. To name a range
of characters, use a dash. [a-z] matches any lowercase letter,
whereas [0-9] matches any digit.
 * matches zero or more instances of the thing preceding it. For
example, x* matches any number of x characters, [0-9]*
matches any number of digits, and .* matches any number of
anything.
 To anchor a pattern so that it must match the beginning or end
of the value being tested, use ^ at the beginning or $ at the end
of the pattern.

Dr.Mareeswari V/SITE/VIT University/ Vellore 58


Reg Ex Example
 To find names beginning with b, use ^ to match the beginning of
the name:

mysql> SELECT * FROM pet WHERE name REGEXP "^b";


+--------+--------+---------+------+------------+------------+
| name | owner | species | sex | birth | death |
+--------+--------+---------+------+------------+------------+
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 |
+--------+--------+---------+------+------------+------------+

Dr.Mareeswari V/SITE/VIT University/ Vellore 59


Reg Ex Example
 To find names ending with `fy', use `$' to match the end of the
name:
mysql> SELECT * FROM pet WHERE name REGEXP "fy$";
+--------+--------+---------+------+------------+-------+
| name | owner | species | sex | birth | death |
+--------+--------+---------+------+------------+-------+
| Fluffy | Harold | cat | f | 1993-02-04 | NULL |
| Buffy | Harold | dog | f | 1989-05-13 | NULL |
+--------+--------+---------+------+------------+-------+

Dr.Mareeswari V/SITE/VIT University/ Vellore 60


Counting Rows
 Databases are often used to answer the question, "How often does
a certain type of data occur in a table?"
 For example, you might want to know how many pets you have, or
how many pets each owner has.
 Counting the total number of animals you have is the same
question as “How many rows are in the pet table?” because there is
one record per pet.
 The COUNT() function counts the number of non-NULL results.

Dr.Mareeswari V/SITE/VIT University/ Vellore 61


Counting Rows Example
 A query to determine total number of pets:
mysql> SELECT COUNT(*) FROM pet;
+----------+
| COUNT(*) |
+----------+
| 9 |
+----------+

Dr.Mareeswari V/SITE/VIT University/ Vellore 62


PHP with MYSQL Steps:
1. connect to mysql from php
 $con=mysql_connect(servername,username,password); -> older version
 $con=mysqli_connect(servername,username,password); -> newer version

2. Select db
 $dbname="";
 mysql_select_db($dbname,$con); -> older version
 mysqli_select_db($con,$dbname); -> newer version

3. Execute query
 $query="";
 $result=mysql_query($query,$con); -> older version
 $result=mysqli_query($con,$query); -> newer version

63 Dr.Mareeswari V/SITE/VIT University/ Vellore


4. fetch records
 mysql_fetch_row($result) -> older version
 mysqli_fech_row($result) -> newer version

 mysql_fetch_array($result) -> older version
 mysqli_fech_array($result) -> newer version

 mysql_fetch_assoc($result) -> older version
 mysqli_fech_assoc($result) -> newer version
5. close and error

 mysql_close($con); -> older version
 mysqli_close($con); -> newer version

 mysql_error(); -> older version
 mysqli_error(); -> newer version

64 Dr.Mareeswari V/SITE/VIT University/ Vellore


Open a connection
 mysqli_connect(host,username,password,dbname);

Parameter Description

host Optional. Either a host name or an IP address

username Optional. The MySQL user name

password Optional. The password to log in with

dbname Optional. The default database to be used when


performing queries

65 Dr.Mareeswari V/SITE/VIT University/ Vellore


F:\xampp\htdocs\programs\creadb.php
<?php
echo "Creation of student1 <br>"; echo ".........................................<br>";
$servername = "127.0.0.1"; $username = "root"; $password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) { die("Connection failed: " . mysqli_error()); }
// Create database
$sql = "CREATE DATABASE students1";
if (mysqli_query($conn,$sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
} mysqli_close($conn);
?>

66 Dr.Mareeswari V/SITE/VIT University/ Vellore


Auto Increment
$sql = "CREATE TABLE Persons
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
FirstName CHAR(15),
LastName CHAR(15),
Age INT
)";

67 Dr.Mareeswari V/SITE/VIT University/ Vellore


<?php
$dbserver="localhost"; $username="root";
$password=""; $databasename="student";
$connection=mysqli_connect($dbserver,$username,$password,$databa
sename) or die ("Error in database connection");
$query="select * from company";
$result=mysqli_query($connection,$query) or die("Error in database
reading");
while($row=mysqli_fetch_row($result))
{ echo "Company Name:$row[0]<br>";
echo "No.of Workers:$row[1]<br>";
echo "Date:$row[2]<br><br><br>";
}mysqli_close($connection); ?>
68 Dr.Mareeswari V/SITE/VIT University/ Vellore
http://localhost/db_student.php
Company Name:CTS
No.of Workers:5000
Date:2014-03-10

Company Name:TCS
No.of Workers:4000
Date:2014-04-14

In Lab : StartAll Programs Appserv MySql command client


Stored in : D:AppservMySQLdata

69 Dr.Mareeswari V/SITE/VIT University/ Vellore


while($row=mysqli_fetch_assoc($result)) {
extract($row);
echo "Company Name:$Name<br>";
echo "No.ofWorkers:$Workers<br>";
echo "Date:$DOJ<br><br><br>"; }

while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "</tr>";
}

70 Dr.Mareeswari V/SITE/VIT University/ Vellore


What will the different functions return?
 All of the mentioned functions will return an array, the differences
between them is what values that are being used as keys in the returned
object.
 mysql_fetch_row
This function will return a row where the values will come in the order as
they are defined in the SQL query, and the keys will span from 0 to one less
than the number of columns selected.
 mysql_fetch_assoc
This function will return a row as an associative array where the column
names will be the keys storing corresponding value.
 mysql_fetch_array
This function will actually return an array with both the contents of
mysql_fetch_row and mysql_fetch_assoc merged into one. It will both have
numeric and string keys which will let you access your data in whatever way
you'd find
71
easiest.
Dr.Mareeswari V/SITE/VIT University/ Vellore
form_student.php
<html>
<body>
<form action="db_student.php" method="post" >
Company Name <input type=text name=cname><br>
No.of Workers <input type=text name=nw><br>
Date<input type=text name=date><br>
<input type=submit name=submit value=Insert>
</form></body></html>

72 Dr.Mareeswari V/SITE/VIT University/ Vellore


Program : form_student.php
Insertion
Program : db_student.php
$CName=$_POST['cname'];
$NW=$_POST['nw']; MySQL : student (Database) 
company (Table)
$Date=$_POST['date'];

$iquery="INSERT INTO company VALUES


('$CName','$NW','$Date')";
mysqli_query($connection,$iquery);

// escape variables for security


$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
73 Dr.Mareeswari V/SITE/VIT University/ Vellore
Queries
 CREATE TABLE table_name(field_name);
 INSERT INTO table_nameVALUES (value1, value2..);
 SELECT * FROM table_name;
 SELECT column_names FROM table_name;
 UPDATE table_name Set colunm_name = new_value
WHERE column_name = some_name;
 DELETE FROM table_nameWHERE column_name =
some_name;
 DESC table_name;

74 Dr.Mareeswari V/SITE/VIT University/ Vellore


 Write MYSQL queries for the following :
 Create a table ‘Student’ with the fields RegNo, Name, Mark1,
Mark2, Mark3, Average and Result.
 Insert values for the record except Average and Result fields.
 Set Result as ‘pass’ when mark1,mark2 and mark3 are more
than 49 marks and set Result as ‘fail’ when mark1,mark2 and
mark3 are less than 50 marks.
 List number of students having result as ‘pass’ and number of
students having result as ‘fail’
 Remove the last record from the table.
 Update the record with your own conditions.

75 Dr.Mareeswari V/SITE/VIT University/ Vellore


Exercise
Create a table Emp with id-integer(3), name- varchar(30), dob-
date, dept - varchar(20), salary – double as fields.
a. Insert some records into the table.
b. Update salary with 10% hike those who got more than 30000.
c. List the number of records in each department
d. List the minimum salary of every department
e. Find the average salary
f. Delete a record whose id is 45
g. List the employees who born in the month of March
h. List the employees whose name starts with ‘A’
i. List the employees whose name length is 5 and starts with S.

76 Dr.Mareeswari V/SITE/VIT University/ Vellore


 Develop a PHP program to insert a record into Emp table with
necessary checking conditions. Develop a HTML page to get
input for those fields.
 Develop a page to populate id’s as a list and let user can choose
an id from list. Develop a PHP program to remove a record from
Emp table.
 Design a page to list the departments uniquely and let the user
chose a department. Develop a PHP program to display
employees belong to the selected department in HTML table
format.

77 Dr.Mareeswari V/SITE/VIT University/ Vellore


By using a MySQL table to store the light bulb jokes. Create a
MySQL database that contains one table. The jokes table stores the
light bulb jokes. For each joke, the table stores the joke's subject
(e.g., professors, computer scientists) and the joke's punch line.
Populate the table with sample data. Write a PHP program that will
display a titled web page that presents the jokes in an HTML table.

78 Dr.Mareeswari V/SITE/VIT University/ Vellore


79 Dr.Mareeswari V/SITE/VIT University/ Vellore
80 Dr.Mareeswari V/SITE/VIT University/ Vellore

You might also like