PHP&MySQL - Unit 1&unit 2
PHP&MySQL - Unit 1&unit 2
Unit - I
Unit – II
Page 1 of 39
Unit – 1
Introduction
PHP
PHP is a server-side scripting language. It is used to develop Static websites or Dynamic
websites or Web applications.
PHP stands for Hypertext Pre-processor, that earlier stood for Personal Home Pages.
PHP scripts can only be interpreted on a server that has PHP installed.
The client computers accessing the PHP scripts require a web browser only.
A PHP file contains PHP tags and ends with the extension ".php".
Characteristics of PHP
There are many features given by PHP. All Features discussed below one by one.
Familiarity
Simplicity
Efficiency
Security
Flexibility
Open source
Object Oriented
Familiarity:
If you are in programming background then you can easily understand the PHP syntax.
And you can write PHP script because of most of PHP syntax inherited from other languages like
C or Pascal.
Simplicity:
Page 2 of 39
PHP provides a lot of pre-define functions to secure your data. It is also compatible with
many third-party applications, and PHP can easily integrate with other.
In PHP script there is no need to include libraries like c, special compilation directives
like Java, PHP engine starts execution from (<?) escape sequence and end with a closing escape
sequence (<?). In PHP script, there is no need to write main function. And also you can work
with PHP without creating a class.
Efficiency:
PHP 4.0 introduced resource allocation mechanisms and more pronounced support for
object-oriented programming, in addition to session management features. Eliminating
unnecessary memory allocation.
Security:
Several trusted data encryption options are supported in PHP’s predefined function set.
You can use a lot of third-party applications to secure data, allowing for securing application.
Flexibility: -
PHP is a very flexible language because PHP is an embedded language you can embed
PHP scripts with HTML, JAVA SCRIPT, WML, XML, and many others. You can run your PHP
script on any device like mobile Phone, tabs, laptops, PC and others because of PHP script
execute on the server then after sending to the browser of your device.
Free:
PHP is an open source programming language so you can download freely there is no
need to buy a licence or anything.
Object Oriented
PHP has added some object-oriented programming features, and Object Oriented
programming became possible with PHP 4. With the introduction of PHP 5, the PHP developers
have really beefed up the object-oriented features of PHP, resulting in both more speed and
added features.
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
The variable $txt will hold the value Hello world! the variable $x will hold the value
5, and the variable $y will hold the value 10.5.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, car
name, total volume).
Page 3 of 39
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example:
<?php
$txt = "Hello World!";
echo "Welcome To $txt!";
?>
Output:
Welcome To Hello World!
The following example will produce the same output as the example above:
<?php
$txt = "Hello World";
echo "Welcome To " . $txt. "!";
?>
Output: Welcome To Hello World!
Example:
Page 4 of 39
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo"<p>Variable x inside function is: $x</p>";
}
myTest();
Output:
Variable x inside function is:
Variable x outside function is: 5
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
Example:
<?php
function myTest() {
$x = 5; // local scope
echo"<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo"<p>Variable x outside function is: $x</p>";
?>
Output:
Variable x inside function is:
5 Variable x outside function
is:
You can have local variables with the same name in different functions, because local
variables are only recognized by the function in which they are declared.
Global Keyword
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example:
<?php
$x = 5;
$y = 10;
functionmyTest()
{ global $x, $y;
$y = $x + $y;
}
Page 5 of 39
myTest();
echo $y; // outputs 15
?>
Static Keyword
Normally, when a function is completed / executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
Example:
<?php
function myTest()
{ static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Output: 0 1 2
Then, each time the function is called, that variable will still have the information it
contained from the last time the function was called.
Page 6 of 39
PHP supports the following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP String
A string is a sequence of characters, like "Hello world!". A string can be any text inside
quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello
world!';echo $x;
echo"<br>";
echo $y;
?>
Outpu
t Hello
World Hello
World
PHP Integer
Page 7 of 39
Example
: <?php
$x = 5985;
var_dump($x);
?>
Output
int (5985)
PHP Float
A float (floating point number) is a number with a decimal point or a number in
exponential form.
In the following example $x is a float. The PHP var_dump () function returns the data
type and value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
Output:
float (10.365)
PHP Boolean
$x=true;
$y = false;
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump () function returns the
data type and value:
<?php
$cars =
array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Output
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
PHP Object
Page 8 of 39
An object is a data type which stores data and information on how to process that data. In
PHP, an object must be explicitly declared. First we must declare a class of object. For this,
we use the class keyword.
<?php
class Car
{
function Car () {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
// show object
properties echo $herbie-
>model;
?>
Output: VW
Output: NULL
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to
functions and resources external to PHP. A common example of using the resource data type is a
database call.
PHP Operators
Operators are used to perform operations on variables and values.
Page 9 of 39
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
x=y x=y The left operand gets set to the value of the expression
Page 10 of 39
on the right
x += y x=x+y Addition
x -= y x=x–y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
Page 11 of 39
< Less than $x < $y Returns true if $x is less than $y
Page 12 of 39
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.
Concatenation of
. Concatenation $txt1 . $txt2 $txt1 and $txt2
Concatenatio
.= n assignment $txt1 .= $txt2 Appends $txt2 to $txt1
Page 13 of 39
Page 14 of 39
PHP Array Operators
The PHP array operators are used to compare arrays.
Conditional statements are used to perform different actions based on different conditions.
Page 15 of 39
Syntax
if (condition)
{
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
Example
<?php
$t = date("H");
if ($t <"20") {
echo"Have a good day!";
}
?>
The if .. else statement executes some code if a condition is true and another code if that
condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20,
and "Have a good night!" otherwise:
Page 16 of 39
Syntax
if (condition)
{
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than
10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a
good night!":
Example
<?php
$t = date("H");
if ($t <"10") {
echo"Have a good morning!";
} elseif ($t <"20") {
echo"Have a good
day!";
} else {
echo"Have a good night!";
}
?>
Syntax
switch (n)
{
caselabel1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
Page 17 of 39
code to be executed if n=label3;
break;
Default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break to
prevent the code from running into the next case automatically. The default statement is used if
no match is found.
Example
<?php
$favcolor =
"red"; switch
($favcolor){
case “red":
echo “Your favoritecolor is
red!"; break;
case"blue":
echo"Your favoritecolor is
blue!"; break;
case"green":
echo"Your favoritecolor is
green!"; break;
default:
echo"Your favoritecolor is neither red, blue, nor green!";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again in
a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a
task like this.
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
for each - loops through a block of code for each element in an array
Page 18 of 39
The PHP while Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax
while (condition is true)
{
code to be executed;
}
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will
continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1 each time
the loop runs ($x++):
Example
<?php
$x = 1;
while($x <= 5)
{
echo"The number is: $x <br>";
$x++;
}
?>
Output :
Syntax
do
{
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will
write some output, and then increment the variable $x with 1. Then the condition is checked (is
$x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to
5:
Page 19 of 39
Example
<?php
$x =
1;do {
echo"The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Output:
Page 20 of 39
UNIT – II
ARRAYS AND
Array FUNCTIONS
s
An array stores multiple values in one single variable:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
Create an Array in PHP
array();
The following example creates an indexed array named $cars, assigns three elements to it,
and then prints a text containing the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
Page 21 of 39
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
"Joe"=>"43");or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");echo "Peter is " . $age['Peter'] . " years
old.";
?>
Example
<?php
$cars = array("Volvo", "BMW",
"Toyota");sort($cars);
?>
The following example sorts the elements of the $numbers array in ascending numerical
order:
Example
Page 22 of 39
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>
Sort Array in Descending Order - rsort()
The following example sorts the elements of the $cars array in descending alphabetical
order:
Example
<?php
$cars = array("Volvo", "BMW",
"Toyota");rsort($cars);
?>
The following example sorts the elements of the $numbers array in descending
numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>
Sort Array (Ascending Order), According to Value - asort()
The following example sorts an associative array in ascending order, according to the
value:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");asort($age);
?>
Sort Array (Ascending Order), According to Key - ksort()
The following example sorts an associative array in ascending order, according to the
key:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");ksort($age);
?>
Sort Array (Descending Order), According to Value - arsort()
The following example sorts an associative array in descending order, according to the
value:
Example
Page 23 of 39
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");arsort($age);
?>
Sort Array (Descending Order), According to Key - krsort ()
The following example sorts an associative array in descending order, according to the
key:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37",
"Joe"=>"43");krsort($age);
?>
Page 24 of 39
UNIT – III
FILE
HANDLING
File handling is an important part of any web application. You often need to open and
process a file for different tasks.
PHP Manipulating Files
PHP has several functions for creating, reading, uploading, and editing files.
PHP readfile() Function
The readfile() function reads a file and writes it to the output buffer.
Assume we have a text file called "webdictionary.txt", stored on the server, that looks like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup
Language PHP = PHP Hypertext Pre-
processor SQL = Structured Query
Language SVG = Scalable Vector
Graphics
XML = EXtensibleMarkup Language
The PHP code to read the file and write it to the output buffer is as follows (the readfile ()
function returns the number of bytes read on success)
Example
<?php
echo readfile("webdictionary.txt")
?>
R Open a file for read only. File pointer starts at the beginning of the file
W Open a file for write only. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
Page 25 of 39
A Open a file for write only. The existing data in file is preserved. File pointer starts at the end of
the file. Creates a new file if the file doesn't exist
X Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't
exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end
of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
The first parameter of fread() contains the name of the file to read from and the second
parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
The fclose () requires the name of the file (or a variable that holds the filename) we want to
close:<?php
$myfile = fopen ("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
PHP Read Single Line - fgets ()
The example below outputs the first line of the "webdictionary.txt" file:
Example
Page 26 of 39
<?php
$myfile = fopen ("webdictionary.txt", "r") or die ("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a
file is created using the same function used to open files.
If you use fopen () on a file that does not exist, it will create it, given that the file is
opened for writing (w) or appending (a).
The example below creates a new file called "testfile.txt". The file will be created in the
same directory where the PHP code resides:
Example
If you are having errors when trying to get this code to run, check that you have granted
your PHP file access to write information to the hard drive.
The example below writes a couple of names into a new file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we
sent the string $txt that first contained "John Doe" and second contained "Jane Doe". After we
finished writing, we closed the file using the fclose () function.
Page 27 of 39
If we open the "newfile.txt" file it would look like this:
John Doe
Jane Doe
Cookie
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the cookie
too. With PHP, you can both create and retrieve cookie values.
Create Cookies With PHP
A cookie is created with the set cookie () function.
Syntax
setcookie (name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
PHP Create/Retrieve a Cookie
The following example creates a cookie named "user" with the value "John Doe". The cookie will
expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website
(otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also
use the isset()function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name. "' is not set!";
} else {
echo "Cookie '" . $cookie_name. "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: The setcookie () function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URL encoded when sending the cookie, and automatically
decoded when received (to prevent URL encoding, use setrawcookie () instead).
Page 28 of 39
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name. "' is not set!";
} else {
echo "Cookie '“. $cookie_name. "' is set! <br>";
echo "Value is: “. $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie () function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
Page 29 of 39
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Session
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the user’s computer.
What is a PHP Session?
When you work with an application, you open it, do some changes, and then you close
it. This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does
not know who you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favoritecolor, etc). By default, session variables last until the
user closes the browser.
So; Session variables hold information about one single user, and are available to all
pages in one application.
Tip: If you need a permanent storage, you may want to store the data in a database.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
Page 30 of 39
echo "Session variables are set.";
?>
</body>
</html>
Note: The session_start () function must be the very first thing in your document. Before any HTML tags.
Another way to show all the session variable values for a user session is to run the following
code:
Example
<?php
session_start ();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Page 31 of 39
UNIT – IV
EFFECTIVENESS OF MYSQL
What is a Database?
A database is a separate application that stores a collection of data. Each database has
one or more distinct APIs for creating, accessing, managing, searching and replicating the data it
holds.
Other kinds of data stores can also be used, such as files on the file system or large hash
tables in memory but data fetching and writing would not be so fast and easy with those type
of systems.
Table − A table is a matrix with data. A table in a database looks like a simple spreadsheet.
Column − One column (data element) contains data of one and the same kind, for example the
column postcode.
Row − A row (= tuple, entry or record) is a group of related data, for example the data of one
subscription.
Primary Key − A primary key is unique. A key value can not occur twice in one table. With a key,
you can only find one row.
Foreign Key − A foreign key is the linking pin between two tables.
Compound Key
because one column is not sufficiently unique.
Referential Integrity
an existing row.
Page 32 of 39
MySQL Database
MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL
is developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is
becoming so popular because of many good reasons −
MySQL is released under an open-source license. So you have nothing to pay to use it.
MySQL is a very powerful program in its own right. It handles a large subset of the
functionality of the most expensive and powerful database packages.
MySQL works on many operating systems and with many languages including PHP, PERL,
C, C++, JAVA, etc.
MySQL works very quickly and works well even with large data sets.
MySQL is very friendly to PHP, the most appreciated language for web development.
MySQL supports large databases, up to 50 million rows or more in a table. The default
file size limit for a table is 4GB, but you can increase this (if your operating system can
handle it) to a theoretical limit of 8 million terabytes (TB).
MySQL is customizable. The open-source GPL license allows programmers to modify the
MySQL software to fit their own specific environments.
MySQL uses many different data types broken into three categories −
Numeric
Date and Time
String Types.
Numeric Data Types
MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL
from a different database system, these definitions will look familiar to you.
The following list shows the common numeric data types and their descriptions −
INT
A normal-sized integer that can be signed or unsigned. If signed, the allowable range is
from -2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295.
You can specify a width of up to 11 digits.
Page 33 of 39
TINYINT
A very small integer that can be signed or unsigned. If signed, the allowable range is
from -128 to 127. If unsigned, the allowable range is from 0 to 255. You can specify a width of
up to 4 digits.
SMALLINT
A small integer that can be signed or unsigned. If signed, the allowable range is from -
32768 to 32767. If unsigned, the allowable range is from 0 to 65535. You can specify a width of
up to 5 digits.
MEDIUMINT
A medium-sized integer that can be signed or unsigned. If signed, the allowable range is
from -8388608 to 8388607. If unsigned, the allowable range is from 0 to 16777215. You can
specify a width of up to 9 digits.
BIGINT
A large integer that can be signed or unsigned. If signed, the allowable range is from -
9223372036854775808 to 9223372036854775807. If unsigned, the allowable range is from 0 to
18446744073709551615. You can specify a width of up to 20 digits.
FLOAT(M,D)
A floating-point number that cannot be unsigned. You can define the display length (M)
and the number of decimals (D). This is not required and will default to 10,2, where 2 is the
number of decimals and 10 is the total number of digits (including decimals). Decimal precision
can go to 24 places for a FLOAT.
DOUBLE(M,D)
A double precision floating-point number that cannot be unsigned. You can define the
display length (M) and the number of decimals (D). This is not required and will default to 16,4,
where 4 is the number of decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is
a synonym for DOUBLE.
DECIMAL(M,D)
An unpacked floating-point number that cannot be unsigned. In the unpacked decimals,
each decimal corresponds to one byte. Defining the display length (M) and the number of
decimals (D) is required. NUMERIC is a synonym for DECIMAL.
Date andTime Types
The MySQL date and time data types are as follows −
DATE
A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example,
December 30th, 1973 would be stored as 1973-12-30.
Page 34 of 39
DATE TIME
A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01
00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973
would be stored as 1973-12-30 15:30:00.
TIME STAMP
A timestamp between midnight, January 1st, 1970 and sometime in 2037. This looks like
the previous DATETIME format, only without the hyphens between numbers; 3:30 in the
afternoon on December 30th, 1973 would be stored as 19731230153000
(YYYYMMDDHHMMSS).
TIME
Stores the time in a HH:MM:SS format.
YEAR(M)
Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for example
YEAR(2)), YEAR can be between 1970 to 2069 (70 to 69). If the length is specified as 4, then
YEAR can be 1901 to 2155. The default length is 4.
String Types
Although the numeric and date types are fun, most data you'll store will be in a string
format. This list describes the common string datatypes in MySQL.
CHAR(M)
A fixed-length string between 1 and 255 characters in length (for example CHAR(5)),
right-padded with spaces to the specified length when stored. Defining a length is not required,
but the default is 1.
VARCHAR(M)
A variable-length string between 1 and 255 characters in length. For example,
VARCHAR(25). You must define a length when creating a VARCHAR field.
BLOB or TEXT
A field with a maximum length of 65535 characters. BLOBs are "Binary Large Objects"
and are used to store large amounts of binary data, such as images or other types of files. Fields
defined as TEXT also hold large amounts of data. The difference between the two is that the
sorts and comparisons on the stored data are case sensitive on BLOBs and are not case
sensitive in TEXT fields. You do not specify a length with BLOB or TEXT.
TINYBLOB or TINYTEXT
A BLOB or TEXT column with a maximum length of 255 characters. You do not specify a
length with TINYBLOB or TINYTEXT.
MEDIUMBLOB or MEDIUMTEXT
A BLOB or TEXT column with a maximum length of 16777215 characters. You do not
specify a length with MEDIUMBLOB or MEDIUMTEXT.
LONGBLOB or LONGTEXT
Page 35 of 39
A BLOB or TEXT column with a maximum length of 4294967295 characters. You do not
specify a length with LONGBLOB or LONGTEXT.
ENUM
An enumeration, which is a fancy term for list. When defining an ENUM, you are
creating a list of items from which the value must be selected (or it can be NULL). For example,
if you wanted your field to contain "A" or "B" or "C", you would define your ENUM as ENUM
('A', 'B', 'C') and only those values (or NULL) could ever populate that field.
To begin with, the table creation command requires the following details −
Name of the table
Name of the fields
Definitions for each field
Syntax
Here is a generic SQL syntax to create a MySQL table −
submission_date DATE,
);
Page 36 of 39
UNIT - V
PHP WITH MYSQL
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to connect to the
server:
We will create a table named "MyGuests", with five columns: "id", "firstname",
"lastname", "email" and "reg_date":
After the data type, you can specify other optional attributes for each column:
NOT NULL - Each row must contain a value for that column, null values are not allowed
DEFAULT value - Set a default value that is added when no other value is passed
UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time
a new record is added
PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY
KEY setting is often an ID number, and is often used with AUTO_INCREMENT
Each table should have a primary key column (in this case: the "id" column). Its value
must be unique for each record in the table.
The INSERT INTO statement is used to add new records to a MySQL table:
Page 37 of 39
Now, let us fill the table with data.
Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP (like the
"reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically
add the value.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
Page 38 of 39
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows> 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Output:
id: 1 - Name: John Doe
id: 2 - Name: Mary Moe
id: 3 - Name: Julie Dooley
Delete Data From a MySQL Table Using MySQLi
The following examples delete the record with id=3 in the "MyGuests" table:
Example (MySQLi)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli ($servername, $username, $password, $dbname);
Page 39 of 39
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Page 40 of 39