SlideShare a Scribd company logo
1 of 98
PHP, MySQL
&
WORDPRESSA study material for B.Sc (Computer Science)
With this book we can learn how to install PHP, APACHE and MySQL
or XAMPP. And developing web pages using PHP. Maintaining
database with MySQL and combining PHP code with MySQL. And can
learn Wordpress to create websites.
D.SULTHAN BASHA M.Sc
s4s
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 1
Q) What is MySQL?
Ans: MySQL is the most popular Open Source Relational SQL Database Management
System. MySQL is one of the best RDBMS being used for developing various web-based
software applications. MySQL is developed, marketed and supported by MySQL AB.
Q) Explain Current Versions and Features of MYSQL
Ans: MySQL supports the current version MySQL 5.7. This version release notes contains the
all the previous decorticated functions and newly added features. The following features are
there in current version of MySQL 5.7.
1. Performance & Scalability: Improved Innovative DB scalability and temporary table
performance, enabling faster online and bulk load operations, and more.
2. JSON (Java Script Object Notation) Support: With the newly added JSON support in
MySQL, you can now combine the flexibility of NoSQL with the strength of a relational
database.
3. Replication improvements for increased availability and performance. They include multi-
source replication, multi-threaded slave enhancements
4. Performance Schema delivering much better and new monitoring capabilities, reduced
the footprint and overhead, and significantly improved ease of use with the new Schema.
5. Security: Fulfilling "secure by default" requirements and many new MySQL 5.7 features
will help users keep their database secure.
6. Optimizer: We have rewritten large parts of the parser, optimizer, and cost model. This
has improved maintainability, expendability, and performance.
Q) How to Get MySQL?
Ans: MySQL AB was the name of the company that developed, maintained, and distributed
the MySQL database server; through a series of acquisitions (Sun Microsystems purchased
MySQL AB, and Oracle Corporation purchased Sun Microsystems), database giant Oracle
now owns MySQL. However, the MySQL Community Edition of the software remains open
source, is supported by open source developers, and is freely available on the MySQL
website at http://www.mysql.com/. Binary distributions for all platforms, installer packages
for Mac OS X, and RPMs and source code files for Linux/UNIX platforms are all available.
Q) How to Install and Configure MySQL?
Ans: MySQL can be installed and configured with different platforms.
1. MySQL Installation on Linux/UNIX: The process of installing MySQL on Linux/UNIX is
straightforward, whether you use RPMs or install the binaries. If you are installing from
RPMs, there are platform specific RPMs such as those for generic Linux running on different
processor types, such as x86 32- and 64-bit.
To perform a minimal installation from RPMs, type the following at your prompt:
# rpm -i MySQL-server-VERSION.i386.rpm MySQL-client-VERSION.i386.rpm
Another painless (and very common) installation method is to install MySQL from a
binary distribution. This method requires the gunzip and tar utilities to uncompress and
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 2
unpack the distribution, and also requires the ability to create groups and users on the
system. The first series of commands in the binary distribution installation process has you
adding a group and a user and unpacking the distribution, as follows:
# groupadd mysql
# useradd -r -g mysql mysql
# cd /usr/local
# tar zxvf /path/to/mysql-VERSION-PLATFORM.tar.gz
2. MySQL Installation on Windows: The MySQL installation process on Windows uses a
standard Microsoft Windows Installer (MSI) file to walk you through the installation and
configuration of
MySQL on your Windows XP, Windows Server 2003, Windows Vista, or Windows 7 machine.
Go to the MySQL downloads page at http://dev.mysql.com/downloads/mysql/ 5.5.html and
select the Windows option from the drop-down menu. Download the Windows MSI Installer
file for your system, either 32- or 64-bit.
* The Security Options configuration screen is the most important screen of all. As shown in
Figure 2.10, use this configuration screen to set a root password. Enter the password twice
to confirm it.
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 3
Q) How to Troubleshoot MySQL Installation?
Ans: The following are just a few of the common installation problems:
 On Linux/UNIX and Mac OS X, incorrect permissions do not allow you to start the
MySQL daemon. If this is the case, be sure that you have changed owners and groups
to match those indicated in the installation instructions.
 If you see the message Access denied when connecting to MySQL, be sure that you
are using the correct username and password.
 If you see the message Can't connect to server, make sure that the MySQL daemon is
running.
Q) Explain about Basic Security Guidelines in MySQL?
Ans: Regardless of whether you are running MySQL on Windows, Linux/UNIX, or Mac OS X,
and no matter whether you administer your own server or use a system provided to you by
your Internet service provider.
Starting MySQL: Securing MySQL begins with the server start-up procedure. If you are not
the administrator of the server, you cannot change this, but you can certainly check it out
and report vulnerabilities to your Internet service provider.
Securing Your MySQL Connection: We can connect to the MySQL monitor (command-line
interface) or other MySQL applications in several different ways, each of which has its own
security risks. If your MySQL installation is on your own workstation.
 If MySQL is installed on your workstation, your biggest security concern is leaving
your workstation unattended with your MySQL monitor or MySQL GUI
administration tool up and running.
 If MySQL is installed on a server outside your network, the security of the connection
should be of some concern. As with any transmission of data over the Internet, data
can be intercepted. If the transmission is unencrypted, the person who intercepted
the data can piece it together and use the information. By using SSH (Secure Shell)
connection mode we can avoid this issues.
Q) Explain about MySQL Privilege System (or) How to add users in MySQL?
Ans: There are several privilege-related tables in the mysql database, such as the following:
 columns_priv-Defines user privileges for specific fields within a table
 db-Defines the permissions for all databases on the server
 host-Defines the acceptable hosts that can connect to a specific database
 procs_priv-Defines user privileges for stored routines
 tables_priv-Defines user privileges for specific tables within a database
 user-Defines the command privileges for a specific user
Understanding the Two-Step Authentication Process:
MySQL checks three things during the authentication process.
The actions associated with above three things are performed in two steps:
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 4
Step: 1. MySQL looks at the host you are connecting from and the username and password
pair you are using. If correct id, password then MySQL moves to the second step.
Step: 2. For whichever SQL command you are attempting to use, MySQL verifies that your
user has permissions to perform that action for that database, table, and field.
If step 1 fails, you see an error about it and you cannot continue on to step 2. For
example, suppose that you are connecting to MySQL with a username of joe and a password
of abc123 and you want to access a database called myDB. You will receive an error
message if any of those connection variables is incorrect for any of the following reasons:
 Your password is incorrect.
 Username joe doesn't exist.
 User joe can't connect from localhost.
 User joe can connect from localhost but cannot use the myDB database.
If user joe with a password of abc123 is allowed to connect from localhost to the myDB
database, MySQL checks the actions that joe can perform in step 2 of the process.
Adding Users to MySQL:
The simplest method for adding new users is the GRANT command. The simple syntax of the
GRANT command is shown here:
Following are some of the common privileges you can grant
 ALL-Gives the user all common privileges.
 ALTER-User can alter (modify) tables, columns, and indexes.
 CREATE-User can create databases and tables.
 DELETE-User can delete records from tables.
 DROP-User can drop (delete) tables and databases.
 FILE-User can read and write files; this privilege is used to import or dump data.
 INDEX-User can add or delete indexes.
 INSERT-User can add records to tables.
 PROCESS-User can view and stop system processes; only trusted users should be
able to do this.
 RELOAD-User can issue FLUSH statements; only trusted users should be able to do
this.
 SELECT-User can select records from tables.
 SHUTDOWN-User can shut down the MySQL server; only trusted users should be
able to do this.
 UPDATE-User can update (modify) records in tables.
If, for instance, you want to create a user called john with a password of 99hjc!5, with
SELECT and INSERT privileges on all tables in the database called myDB, and you want this
user to be able to connect from any host, use this command:
GRANT privileges
ON databasename.tablename TO username@host IDENTIFIED BY
"password";
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 5
Note the use of two wildcards: * and %. These wildcards replace values. In this example, *
replaces the entire list of tables, and % replaces a list of all hosts in the known world-a very
long list indeed.
Here's another example of adding a user with the GRANT command, this time to add
a user called jane with a password of 45sdg11, with ALL privileges on a table called
employees
Removing User Privileges: Removing privileges is as simple as adding them; instead of the
GRANT command, you use REVOKE. The REVOKE command syntax is as follows:
Q) Explain Apache Web Server and its Current Version and Features
Ans: Apache is the actual web server application that processes and delivers web content to
a computer. Apache is the most popular web server online, powering nearly 54% of all
websites. The Apache HTTPD server website at http://httpd.apache.org shows
announcements for releases of the Apache 2.0.x, Apache 2.2.x, and Apache 2.4.x versions.
As you can understand by the version numbers, Apache 2.0.x is the oldest of the three
versions. The Apache Software Foundation maintains all three versions, but the features in
Apache 2.4.x include the latest and greatest.
Apache HTTP Server version 2.4 provides the following notable features:
 The event Multi-Processing Module (MPM) and integrated proxy module support for
the FastCGI protocol allow the server to serve more concurrent requests.
 Improvements to asynchronous read and write handling.
 Embedded scripting.
Installing Apache on Linux/UNIX
This section explains how to install a fresh build of Apache 2.4.1 on Linux/UNIX.
The general steps necessary to successfully install Apache from source are as follows:
1. Download the software.
2. Run the configuration script.
3. Compile the code and install it
GRANT SELECT, INSERT
ON myDB.* TO john@"%"
IDENTIFIED BY "99hjc!5";
GRANT ALL
ON myCompany.employees
TO jane@janescomputer.company.com IDENTIFIED BY "45sdg11";
REVOKE privileges
ON databasename.tablename
FROM username@hostname;
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 6
Installing Apache on Windows:
Apache 2.2 runs on most Windows platforms and offers increased performance and
stability over earlier versions for Windows. You can build Apache from source, but because
not many Windows users have compilers, this section deals with the MSI installer version.
Q) Explain Apache Configuration File Structure
Ans: Apache Configuration File Structure: Apache keeps all its configuration information in
text files. The main file is httpd.conf. This file contains directives and containers that enable
you to customize your Apache installation. Directives configure specific settings of Apache,
such as authorization, performance, and network parameters. Containers specify the
context to which those settings refer.
The Apache documentation for directives typically follows this model:
. Description-This entry provides a brief description of the directive.
. Syntax-This entry explains the format of the directive options. Compulsory parameters
appear in italics, and optional parameters appear in italics and brackets.
. Default-If the directive has a default value, it appears here.
. Context-This entry details the containers or sections in which the directive can appear. The
next section explains containers. The possible values are server config, virtual host, irectory,
and .htaccess.
These are the default Apache containers:
. <VirtualHost>-A VirtualHost directive specifies a virtual server. Apache enables you to host
different websites with a single Apache installation.
. <Directory>, <DirectoryMatch>-These containers allow directives to apply to a certain
directory or group of directories in the filesystem. Directory containers take a directory or
directory pattern argument.
. <Location>, <LocationMatch>-These containers allow directives to apply to certain
requested URLs or URL patterns.
. <Files>, <FilesMatch>-Similar to the Directory and Location containers, Files sections allow
directives to apply to certain files or file patterns.
Q) Explain Apache Log Files and Apache Related Commands
Ans: Apache includes two log files by default. The access_log file is for tracking client
requests. The error_log file is for recording important events, such as errors or server
restarts. These files don't exist until you start Apache the first time. The names of the files
are access.log and error.log in Windows platforms.
The access_log File
When a client requests a file from the server, Apache records several parameters associated
with the request, including the IP address of the client, the document requested, the HTTP
status code, and the current time
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 7
The error_log File
The error_log file includes error messages, startup messages, and any other significant
events in the life cycle of the server. This is the first place to look when you have a problem
with Apache.
On Windows, you can signal Apache using the httpd.exe executable. Some commands are
listed here:
. httpd.exe -k restart-Tells Apache to restart
. httpd.exe -k graceful-Tells Apache to do a graceful restart
. httpd.exe -k stop-Tells Apache to stop
Q) Explain Apache Installation Troubleshoot
Ans:- Already an Existing Web Server If a server is already running on the machine and is
listening to the same IP address and port combination, Apache cannot start successfully.
You will get an entry in the error log file indicating that Apache cannot bind to the port
No Permission to Bind to Port You will get an error if you do not have administrator
permissions and you try to bind to a privileged port (between 0 and 1024):
To solve this problem, you must either log on as the administrator before starting Apache or
change the port number; 8080 is a commonly used nonprivileged port
Access Denied You might not be able to start Apache if you do not have permission to read
the configuration files or to write to the log files.
Q) Explain about the advantages and disadvantages of PHP? Or Explain about the
features of PHP?
Ans: Introduction: PHP stands for Hypertext Preprocessor. PHP is a powerful and widely-
used open source server-side scripting language to write dynamically generated web pages.
PHP scripts are executed on the server and the result is sent to the browser as plain HTML.
[crit] (13)Permission denied: make_sock: could not bind to address 10.0.0.2:80
[alert] no listening sockets available, shutting down
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 8
PHP can be integrated with the number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
PHP can be embedded within a normal HTML web pages. That means inside your HTML
documents you'll have PHP statements like this:
What is PHP
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use
What is a PHP File?
 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP code are executed on the server, and the result is returned to the browser as
plain HTML
 PHP files have extension ".php"
What Can PHP Do?
 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data
Why PHP?
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side
Advantages of PHP
1. Open source: It is developed and maintained by a large group of PHP developers, this will
helps in creating a support community, abundant extension library.
2. Speed: It is relative fast since it uses much system resource.
3. Easy to use: It uses C like syntax, so for those who are familiar with C, it's very easy for
them to pick up and it is very easy to create website scripts.
4. Stable: Since it is maintained by many developers, so when bugs are found, it can be
quickly fixed.
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 9
5. Powerful library support: we can easily find functional modules you need such as PDF,
Graph etc.
6. Built-in database connection modules: You can connect to database easily using PHP,
since many websites are data/content driven, so we will use database frequently, this will
largely reduce the development time of web apps.
7. Can be run on many platforms, including Windows, Linux and Mac, it's easy for users to
find hosting service providers.
Disadvantages of PHP
1. Security: Since it is open sourced, so all people can see the source code, if there are bugs
in the source code, it can be used by people to explore the weakness of PHP.
2. Not suitable for large applications: Hard to maintain since it is not very modular.
3. Weak type: Implicit conversion may surprise unwary programmers and lead to
unexpected bugs. For example, the strings "1000" and "1e3" compare equal because they
are implicitly cast to floating point numbers.
Q) Explain Installation and Configuration of PHP in Linux and Windows
Ans: Installing and Configuring PHP on Linux: To download the PHP distribution files, go to
the home of PHP, http://www.php.net/, and follow the link to the Downloads section. Grab
the latest version of the source code-for this example, we are using 5.4.0. Your distribution
will be named something similar to php-VERSION.tar.gz, where VERSION is the most recent
release number. This archive will be a compressed tar file, so you need to unpack it:
Integrating PHP with Apache on Linux/UNIX
To ensure that PHP and Apache get along with one another, you need to check for and
potentially add-a few items to the httpd.conf configuration file
Add the following line to that section:
This statement ensures that the PHP engine will parse files that end with the .php extension.
PHP is now part of the Apache web server.
Installing and Configuring PHP on Windows: Installing PHP on Windows requires nothing
more than downloading the distribution file. To download the PHP distribution files, go to
the home of PHP on Windows, http://windows.php.net/, and follow the link to the
Downloads page
After the file downloads to your system, double-click it to launch your unzipping
software. The distribution is packed up with relative pathnames already in place, so extract
the files to a new directory called C:php, where it will place all the files and subdirectories
under that new directory. Next, go to the C:php directory and copy the php.ini-
development file to php.ini. Now, to get a basic version of PHP working with Apache, you
need to make a few minor modifications to the Apache configuration file.
# gunzip < php-VERSION.tar.gz | tar xvf –
AddType application/x-httpd-php .php
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 10
Integrating PHP with Apache on Windows
To ensure that PHP and Apache get along with one another, you need to add a few items to
the httpd.conf configuration file. First, find a section that looks like this:
At the end of this section, add the following:
In addition, add the following to ensure Apache knows where php.ini resides:
Add the following line:
This statement ensures that the PHP engine will parse files that end with the .php
extension. Your selection of filenames might differ; for example, you might want to parse all
*.html files as PHP files. Save the httpd.conf file and then restart Apache. The server should
start without warning; PHP is now part of the Apache web server.
Q) Explain Php.ini Basics
Ans: php.ini Basics: After you have compiled or installed PHP, you can still change its
behavior with the php.ini file. On Linux/UNIX systems, the default location for this file is
/usr/local/php/lib or the lib subdirectory of the PHP installation location you used at
configuration time. On a Windows system, this file should be in the PHP directory or another
directory as specified by the value of PHPIniDir in the Apache httpd.conf file.
Directives in the php.ini file come in two forms: values and flags. Value directives take
the form of a directive name and a value separated by an equal sign. Possible values vary
from directive to directive. Flag directives take the form of a directive name and a positive
or negative term separated by an equal sign. Positive terms include 1, On, Yes, and True.
Negative terms include 0, Off, No, and False. Whitespace is ignored.
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule access_module modules/mod_access.so
...
#LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule php5_module C:/php/php5apache2_2.dll
PHPIniDir "C:/php/"
Next, look for this section:
#
# AddType allows you to add to or override the MIME configuration
# file mime.types for specific file types.
#
AddType application/x-httpd-php .php
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 11
Q) Explain Basics of PHP Scripts
Ans: When writing PHP, we need to inform the PHP engine that you want it to execute our
commands. If we don't do this, the code you write will be mistaken for HTML and will be
output to the browser. We can designate your code as PHP with special tags that mark the
beginning and end of PHP code blocks. Table 4.1 shows four such PHP delimiter tags.
Combining HTML and PHP
You can incorporate this into an HTML document by simply adding HTML outside the PHP
start and end tags, as shown in Listing 4.2.
Q) Explain Basics Building Blocks of PHP (or) Explain Datatypes in PHP
Ans: Variable: A variable is a special container that we can define, which then "holds" a
value, such as a number, string, object, array, or a Boolean.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
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)
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 12
Example:
Output:
Datatypes in PHP:
 Different types of data take up different amounts of memory and may be treated
differently when they are manipulated by a script.
 PHP is loosely typed, meaning that it automatically determines the data type at the
time data is assigned to each variable.
 Variables can be used flexibly-in one instance, a variable can hold a string and then
later in the script it can hold an integer or some other data type.
PHP supports the following data types:
<?php $txt = SSGS Degree College";
echo " Welcome to $txt!"; ?>
<?php $x = 5; $y = 4; echo $x + $y; ?>
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 13
Changing Type with settype():-
settype() is used to change the type of a variable. Syntax:-
settype($variabletochange, 'new type');
<?php
$var1='98';
$var2='01'; settype($var1, "integer"); settype($var2, "integer"); echo ($var1.'<br>');
echo ($var2.'<br>');
echo ($var1+$var2.'<br>');
?>
Q) Explain Operators and Expressions in PHP
Ans: An operator is a symbol or series of symbols that, when used in conjunction with
values, performs an action, and usually produces a new value.
PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 14
Arithmetic operators
The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
Assignment operators
The PHP assignment operators are used with numeric values to write a value to a variable.
$x = 4;
$x = $x + 4; // $x now equals 8
Comparison operators
Comparison operators perform comparative tests using their operands and return the
Boolean value true if the test is successful or false if the test fails.
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 15
Increment/Decrement operators
These operators allow us to add or subtract the integer constant 1 from an integer variable,
assigning the result to the variable itself.
String operators
PHP has two operators that are specially designed for strings.
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 16
Array operators:
Q) Explain about Constants in PHP
Ans: A constant is an identifier (name) for a simple value. The value cannot be changed
during the script. A valid constant name starts with a letter or underscore (no $ sign before
the constant name).
Note: Unlike variables, constants are automatically global across the entire script.
Create a PHP Constant
To create a constant, use the define() function.
Syntax
define(name, value, case-insensitive)
Parameters:
1. name: Specifies the name of the constant
2. value: Specifies the value of the constant
3. case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false
The example below creates a constant with a case-sensitive name:
Example
<?php define("GREETING", "Welcome to W3Schools.com!"); echo GREETING; ?>
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 17
Q)Explain about the Switching Flow? Or
Explain about the decision making and branching statements?
Ans: It is common for scripts to evaluate conditions and change their behavior accordingly.
These decisions are what make your PHP pages dynamic-that is, able to change output
according to circumstances.
PHP includes the following switching flow controls.
1. The if Statement
2. Using the else Clause with the if Statement
3. Using the elseif Clause with the if Statement
4. The switch Statement
5. Using the ?: Operator
1. The if Statement :-
Syntax
Example:
2. Using the else Clause with the if Statement: -
Syntax
Example:
if (expression)
{
// code to execute if the expression
evaluates to true
}
<?php $t = date("H");
if ($t < "20")
{ echo "Have a good day!"; } ?>
if (expression)
{
// code to execute if the expression evaluates to
true
}
else
{
// code to execute in all other cases
}
<?php $t = date("H");
if ($t < "20") { echo "Have a good day!";
}
else
{
echo "Have a good night!"; }
?>
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 18
3. Using the elseif Clause with the if Statement:-
Syntax
Example:-
4. The switch Statement :-
Syntax:-
if (expression)
{
// code to execute if the expression evaluates to true
}
elseif (another expression)
{
// code to execute if the previous expression failed
// and this one evaluates to true
}
else
{
// code to execute in all other cases
}
<?php $t = time("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20")
{
echo "Have a good day!";
}
else
{ echo "Have a good night!";
}
>
switch (expression)
{
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 19
Example:-
5. Using the ?: Operator
The ?: or ternary operator is similar to the if statement, except that it returns a value
derived from one of two expressions separated by a colon.
Syntax:-
If the test expression evaluates to true, the result of the second expression is returned;
otherwise, the value of the third expression is returned.
Example:-
Q)Explain about the Loops? Or Iterative statements ?
Ans: Loop statements are specifically designed to enable you to perform repetitive tasks
because they continue to operate until a specified condition is achieved or until we explicitly
choose to exit the loop.
1. The while Statement :-
Syntax :- Example:-
<?php $favcolor = "red";
switch ($favcolor)
{ case "red": echo "Your favorite color is red!";
break;
case "blue": echo "Your favorite color is blue!";
break;
case "green": echo "Your favorite color is green!";
break;
default: echo "Your favorite color is neither red, blue,
nor green!";
} ?>
(expression) ? returned_if_expression_is_true : returned_if_expression_is_false;
<?php
$mood = "sad";
$text = ($mood == "happy") ? "I am in a good mood!" : "I am in
a $mood mood.";
echo "$text";
?>
while (expression)
{
// do something
}
<?php $x = 1;
while ($x <= 5)
{
echo "The number is: $x <br>"; $x++;
} ?>
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 20
2. The do...while Statement :
Syntax:-
Example:-
3. The for Statement
Syntax:-
Example:-
Q)Explain about the Code Blocks and Browser Output?
Ans:-
1. Open a notepad and type the following blocks code. (Start Allprogram notepad)
2. save it as a .php extension under xampp htdocs folder Code Block
do
{
// code to be executed
} while (expression);
<?php $x = 1;
do
{
echo "The number is: $x <br>"; $x++;
} while ($x <= 5);
?>
for (initialization expression; test expression; modification expression)
{
// code to be executed
}
<?php
for ($x = 0; $x <= 10; $x++)
{
echo "The number is: $x <br>";
}
?>
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 21
Run the php program by typing at the address bar of the firefox / chrome browser
localhost/ex2.php the output will be displayed at the browser's document window
Q) What is Function? Explain types of Functions in PHP
Ans: A function is a self-contained block of code that can be called by your scripts. When
called, the function's code is executed and performs a particular task.
Types of Functions: Functions come in two types: those built in to the language and those
you define Yourself (User Defined Functions). PHP has hundreds of built-in functions.
Q) How to Declare User Defined Functions in PHP
Ans: Defining a Function: You can define your own functions using the function statement:
<html>
<head>
<title>Listing 5.14</title>
</head>
<body>
<?php
$display_prices = true;
if ( $display_prices ) {
?>
<table border="1">
<tr><td colspan="3">today's prices in dollars</td></tr>
<tr><td>14</td><td>32</td><td>71</td>
</table>
<?php
}
?>
</body>
</html>
function some_function($argument1, $argument2)
{
//function code here
Return;
}
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 22
The name of the function follows the function statement and precedes a set of parentheses.
A function can return a value using the return statement in conjunction with a value. The
return statement stops the execution of the function and sends the value back to the calling
code.
Q) Explain Scope of Variables in Functions.
Ans: A variable declared within a function remains local to that function. In other words, it is
not available outside the function or within other functions. In larger projects, this can save
you from accidentally overwriting the contents of a variable when you declare two variables
with the same name in separate functions.
Two types of Scope of Variables:
1. Local Variables
2. Global Variables
1. Local variables:- A Variable Declared Within a Function Is Unavailable Outside the
Function
The value of the variable $testvariable is not printed because no such variable exists outside
the test() function.
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 23
2. Global Variables: A variable declare out side function can be used in function by using
global statement.
Ex:
You can declare more than one variable at a time with the global statement by simply
separating each of the variables you want to access with commas: global $var1, $var2,
$var3;
Q) Explain Static Statement in PHP
Ans: Another important feature of variable scoping is the static variable. A static variable
exists only in a local function scope, but it does not lose its value when program execution
leaves this scope. Consider the following example:
Ex:
<?php
$num_of_calls = 0;
function numberedHeading($txt)
{
global $num_of_calls;
$num_of_calls++;
echo "<h1>".$num_of_calls." ".$txt."</h1>";
}
numberedHeading("SSGS Degree College");
echo "<p>Located in Guntakal.</p>";
numberedHeading("courses Offeres");
echo "<p>ALL Degree Gropus</p>";
?>
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 24
Q) Explain More Function Arguments
Ans: Setting Default Values for Arguments: PHP provides a nifty feature to help build flexible
functions.
Passing Variable References to Functions: When you pass arguments to functions, they are
stored as copies in parameter variables. Any changes made to these variables in the body of
the function are local to that function and are not reflected beyond it
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 25
Q) How to Create Arrays in PHP
Ans: Arrays are indexed, which means that each entry is made up of a key and a value. The
key is the index position, beginning with 0 and increasing incrementally by 1 with each new
element in the array
Creating Arrays You can create an array using either the array() function or the array
operator []. The array() function is usually used when you want to create a new array
The following code snippet shows how to create an array called $rainbow using the
array() function, containing all its various colors:
$rainbow = array("red", "orange", "yellow", "green", "blue", "indigo", "violet");
The following snippet shows the same array being created incrementally using the array
operator:
$rainbow[] = "red";
$rainbow[] = "orange";
$rainbow[] = "yellow";
$rainbow[] = "green";
$rainbow[] = "blue";
$rainbow[] = "indigo";
$rainbow[] = "violet";
Both snippets create a seven-element array called $rainbow, with values starting at index
position 0 and ending at index position 6.
Creating Associative Arrays: Whereas numerically indexed arrays use an index position as
the key-0, 1, 2, and so forth-associative arrays use actual named keys. The following
example demonstrates this by creating an array called $character with four elements:
Creating Multi dimensional Arrays: The first two types of arrays hold strings and integers,
whereas this third type holds other arrays. If each set of key/value pairs constitutes a
dimension, a multidimensional array holds more than one series of these key/value pairs
$character = array( "name" => "Bob",
"occupation" => "superhero", "age" => 30,
"special power" => "x-ray vision"
);
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 26
Q) Explain Some Array Related Functions in PHP
Ans: Some Array-Related Constructs and Functions: More than 70 array-related functions
are built in to PHP, which you can read about in detail at http://www.php.net/array. Some
of the more common (and useful) functions are described briefly in this section:
<?php
$characters = array(
array(
"name" => "Bob",
"occupation" => "superhero",
"age" => 30,
"special power" => "x-ray vision"),
array(
"name" => "Sally",
"occupation" => "superhero",
"age" => 24,
"special power" => "superhuman strength"),
array(
"name" => "Jane",
"occupation" => "arch villain",
"age" => 45,
"special power" => "nanotechnology"));
?>
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 27
. count() and sizeof()-Each of these functions counts the number of elements in an array;
they are aliases of each other. Given the following array $colors = array("blue", "black",
"red", "green"); both count($colors); and sizeof($colors); return a value of 4.
. each() and list()-These functions (well, list() is a language construct that looks like a
function) usually appear together, in the context of stepping through an array and returning
its keys and values. You saw an example of this previously, where we stepped through the
$c array and printed its contents.
. foreach()-This control structure (that looks like a function) is used to step through an array,
assigning the value of an element to a given variable, as you saw in the previous section.
Q) How to Create and Work with Objects
Ans: Creating an object is simple; you just declare it to be in existence:
Now that you have a class, you can create a new instance of an object:
output:-
class myClass {
//code will go here
}
$object1 = new myClass();
<?php
class myClass {
//code will go here
}
$object1 = new myClass();
echo "$object1 is an
".gettype($object1).".<br/>";
if (is_object($object1)) {
echo "Really! I swear $object1 is an
object!";
}
?>
$object1 is an object.
Really! I swear $object1 is an object!
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 28
Accessing Class Properties Within a Method: We can access class variables with in functions
Constructors: A constructor is a function that lives within a class and, given the same name
as the class, is automatically called when a new instance of the class is created using new
classname. Using constructors enables you to provide arguments to your class which will
then be processed immediately when the class is called
Q) Explain Object Inheritance
Ans: One class inherits functionality from its parent class A Class Inheriting from Its Parent
If you save this code as inheritance.php, place it in your document root, and access it with
your web browser, you will see the following on your screen:
HELLO! My name is PHP
<?php
class myClass {
public$name = "Sulthan";
function sayHello() {
echo "HELLO! My name is ".$this->name;
}
}
$object1 = new myClass();
$object1 -> sayHello();
?>
<?php
class myClass {
public$name = "Java";
function myClass($n)
{
$this->name = $n;
}
function sayHello()
{
echo "HELLO! My name is ".$this->name;
}
}
class childClass extends myClass
{
//code goes here
}
$object1 = new childClass("PHP");
$object1 -> sayHello();
?>
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 29
Q) How to work with Strings in PHP (or) Explain Conversion Specifiers in PHP
Ans: PHP provides the following conversion specifications
1. Padding Output with a Padding Specifier The padding specifier should directly follow the
percent sign that begins a conversion specification
2. Specifying a Field Width You can specify the number of spaces within which your output
should sit. A field width specifier is an integer that should be placed after the percent sign
that begins a conversion specification
3. Specifying Precision This proves particularly useful when dealing with currency. The
precision identifier should be placed directly before the type specifier. It consists of a dot
followed by the number of decimal places to which you want to round. This specifier has an
effect only on data that is output with the f type specifier:
<?php printf("%04d", 36);
// prints "0036"
?>
<?php
printf("% 4d", 36)
// prints " 36"
?>
<?php
echo "<pre>"; printf("%20sn",
"Books");
printf("%20sn", "CDs");
printf("%20sn", "DVDs");
printf("%20sn", "Games");
printf("%20sn", "Magazines");
echo "</pre>";
?>
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 30
<?php
printf("%.2f", 5.333333);
// prints "5.33"
?>
4. Type Specifier
The printf() function requires
a string argument, known as a format control string. It also accepts additional arguments of
different types, which you learn about in a moment. The format control string contains
instructions regarding the display of these additional arguments
Q) Explain String Handling Functions in PHP
Ans: a string as an array of characters, and thus you can access the individual characters of a
string as if they were elements of an array:
1. strlen(): strlen() might be used to check the length of string
<?php
$test = "phpcoder";
echo $test[0]; // prints "p" echo $test[4]; //
prints "o"
?>
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 31
2. strstr(): the strstr() function to test whether a string exists within another string. This
function requires two arguments: the source string and the substring you want to find
within it.
3. strpos(): The strpos() function requires two arguments: the source string and the
substring you are seeking. The function also accepts an optional third argument, an integer
representing the index from which you want to start searching.
If the substring does not exist, strpos() returns false; otherwise, it returns the index at which
the substring begins
4. substr(): substr() returns only that number of characters, from the start index onward:
<?php
$membership = "pAB7";
if (strlen($membership) == 4) { echo "<p>Thank
you!</p>";
}
else {
echo "<p>Your membership number must be four
characters long.</p>";
}
?>
<?php
$membership = "pAB7";
if (strstr($membership, "AB")) {
echo "<p>Your membership expires
soon!</p>";
} else {
echo "<p>Thank you!</p>";
}
?>
<?php
$membership = "mz00xyz";
if (strpos($membership, "mz") === 0) { echo "Hello mz!";
}
?>
<?php
$test = "phpcoder";
echo substr($test,3)."<br/>"; // prints "coder" echo
substr($test,3,2)."<br/>"; // prints "co"
?>
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 32
5. Strtok(): The function returns the next found token every time it is called, returning false
when the end of the string is reached
Q) How to Manipulate String in PHP (or) Explain trim(),ltrim() functions
Ans:
1.trim(): The trim() function shaves any whitespace characters, including newlines, tabs, and
spaces, from both the start and end of a string.
2. ltrim():The ltrim() function to strip whitespace from only the beginning of a string. this
function with the string you want to transform and it returns a new string, shorn of tabs,
newlines, and spaces
<?php
$test = "http://www.google.com/search?";
$test .= "hl=en&ie=UTF-
8&q=php+development+books&btnG=Google+Search";
$delims = "?&";
$word = strtok($test, $delims);
while (is_string($word)) {
if ($word) {
echo $word."<br/>";
}
$word = strtok($delims);
}
?>
<?php
$text = "ttlots of room to breathe "; echo
"<pre>$text</pre>";
// prints " lots of room to breathe ";
$text = trim($text);
echo "<pre>$text</pre>";
// prints "lots of room to breathe";
?>
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 33
Q)Explain Date and Time Functions in PHP
Ans: The PHP Date() Function: The PHP date() function convert a timestamp to a more
readable date and time.
The syntax of the PHP date() function can be given with. date(format, timestamp)
Example
14/02/2018
Formatting the Dates and Times with PHP: The format parameter of the date() function
is in fact a string that can contain multiple characters allowing you to generate a date string
containing various components of the date and time, like day of the week, AM or PM, etc.
Here are some the date-related formatting characters that are commonly used in format
string:
d - Represent day of the month; two digits with leading zeros (01 or 31)
D - Represent day of the week in text as an abbreviation (Mon to Sun)
m - Represent month in numbers with leading zeros (01 or 12)
M - Represent month in text, abbreviated (Jan to Dec)
y - Represent year in two digits (08 or 18)
Y - Represent year in four digits (2008 or 2018)
The parts of the date can be separated by inserting other characters, like hyphens (-), dots
(.), slashes (/), or spaces to add additional visual formatting.
<?php
$text = "ttlots of room to breathe "; echo
"<pre>$text</pre>";
// prints " lots of room to breathe ";
$text = ltrim($text);
echo "<pre>$text</pre>";
// prints "lots of room to breathe ";
?>
<?php
$today = date("d/m/Y"); echo $today;
?>
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 34
Example
Similarly you can use the following characters to format the time string:
h - Represent hour in 12-hour format with leading zeros (01 to 12)
H - Represent hour in in 24-hour format with leading zeros (00 to 23)
i - Represent minutes with leading zeros (00 to 59)
s - Represent seconds with leading zeros (00 to 59)
a - Represent lowercase ante meridiem and post meridiem (am or pm)
A - Represent uppercase Ante meridiem and Post meridiem (AM or PM)
The PHP code in the following example displays the date in different formats:
Example
The PHP time() Function
The time() function is used to get the current time as a Unix timestamp (the number of
seconds since the beginning of the Unix epoch: January 1 1970 00:00:00 GMT).
Example
The above example produce the output as  1394003958
<?php
echo date("d/m/Y") . "<br>";
echo date("d-m-Y") . "<br>"; echo
date("d.m.Y");
?>
Output:-
14/02/2018
14/02/2018
14/02/2018
<?php
echo date("h:i:s") . "<br>";
echo date("F d, Y h:i:s A") . "<br>"; echo
date("h:i a");
?>
Output:-
04:34:58
February 14, 2018 04:34:58 AM
04:34 am
<?php
// Executed at March 05, 2014 07:19:18
$timestamp = time(); echo($timestamp);
?>
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 35
We can convert this timestamp to a human readable date through passing it to the
previously introduce date() function.
The above example produce the output as  March 05, 2014 07:19:18
The PHP mktime() Function:
The mktime() function is used to create the timestamp based on a specific date and time. If
no date and time is provided, the timestamp for the current date and time is returned. The
syntax of the mktime() function can be given with:
mktime(hour, minute, second, month, day, year)
The following example displays the timestamp corresponding to 3:20:12 pm on May 10, 2014:
Example
The above example produce the output as  1399735212
The mktime() function can be used to find the weekday name corresponding to a
particular date. To do this, simply use the 'l' (lowercase 'L') character with your timestamp,
as in the following example, which displays the day that falls on April 1, 2014:
Example
<?php
// Get the weekday name of a particular date echo date('l', mktime(0,0,0,1,4,2014));
?>
The above example produce the output as  Saturday
The mktime() function can also be used to find a particular date in future after a specific
time period. As in the following example, which displays the date which falls on after 30
month from the current date?
<?php
$timestamp = 1394003958;
echo(date("F d, Y h:i:s", $timestamp));
?>
<?php
// Create the timestamp for a particular date echo
mktime(15, 20, 12, 5, 10, 2014);
?>
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 36
Example
The above example produce the output as  05/09/2016
Q) How to Create Forms in PHP
Ans: HTML forms are the principal means by which substantial amounts of information pass
from the user to the server.
Creating Forms:-
In HTML, we can create forms by using the <form> </form> tag . This tag contains many
internal tabs for creating form elements.
<!DOCTYPE html>
<html>
<head>
<title>A simple HTML form</title> 5: </head>
<body>
<form method="post" action="simpleform.php">
<p><label for="user">Name:</label><br/>
<input type="text" id="user" name="user"></p>
<p><label for="message">Message:</label><br/>
<textarea id="message" name="message" rows="5" cols="40"></textarea></p>
<button type="submit" name="submit" value="send">Send Message</button>
</form>
</body>
</html>
The FORM element's ACTION argument points to a file called simpleform.php, which
processes the form information. The method of this form is POST, so the variables are
stored in the $_POST superglobal
Reading Input from a Form
<!DOCTYPE html>
<html>
<head>
<title>A simple response</title>
</head>
<body>
<p>Welcome, <strong><?php echo $_POST['user']; ?></strong>!</p>
<?php
// Executed at March 05, 2014
$futureDate =
mktime(0,0,0,date("m")+30,date("d"),d
ate("Y"));
echo date("d/m/Y", $futureDate);
?>
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 37
<p>Your message is:
<strong><?php echo $_POST['message']; ?></strong></p>
</body>
</html>
Q) How to Access Form Input with User Defined Arrays
Ans: We can read the multiple inputs by defining form check box as an array which is
defined with in the <input> tag.
Example:-
<input type="checkbox" id="tricorder" name="products[]" value="Tricorder">
An HTML Form Including Multiple Check Boxes
<!DOCTYPE html>
<html>
<head>
<title>An HTML form with checkboxes</title>
</head>
<body>
<form action="send_formwithcb.php" method="POST">
<p><label>Name:</label><br/>
<input type="text" name="user" /></p>
<fieldset>
<legend>Select Some Products:</legend><br/>
<input type="checkbox" id="1101" name="products[]" value="Grinder">
<label for="grinder">Grinder</label><br/>
<input type="checkbox" id="1102" name="products[]" value="Tablemate">
<label for="tablemate">Tablemate</label><br/>
<input type="checkbox" id="1103" name="products[]" value="Printer">
<label for="printer">HAL 2000</label>
</fieldset>
<button type="submit" name="submit" value="submit">Submit Form</button>
</form>
</body>
</html>
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 38
Accessing Form elements using array in PHP: The following php program illustrates how to
access multiple array values.
<!DOCTYPE html>
<html>
<head>
<title>Reading checkboxes</title>
</head>
<body>
<p>Welcome, <strong><?php echo $_POST['user']; ?></strong>!</p>
<p>Your product choices are:
<?php
if (!empty($_POST['products'])) {
echo "<ul>";
foreach ($_POST['products'] as $value) {
echo "<li>$value</li>";
}
echo "</ul>";
}
else {
echo "None";
}
?>
</body>
</html>
Now access the form (formwithcb.html) with your web browser and check some
checkboxes. Figure shows an example
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 39
Q) Explain about Hidden Fields to Save State
Ans: A hidden field behaves the same as a text field, except that the user cannot see it
unless he views the HTML source of the document that contains it. Take the original
numguess.php script and save a copy as numguess2.php. In the new version, add a line after
the initial assignment of the $num_to_guess variable:
$num_tries = (isset($_POST['num_tries'])) ? $num_tries + 1 : 1;
This line initializes a variable called $num_tries and assigns a value to it. If the form has
not yet been submitted (if $_POST['num_tries'] is empty), the value of the $num_tries
variable is 1 because you are on your first attempt at guessing the number. If the form has
already been sent, the new value is the value of $_POST['num_tries'] plus 1.
Saving State with a Hidden Field
<?php
$num_to_guess = 42;
$num_tries = (isset($_POST['num_tries']))
? $num_tries + 1 : 1;
if (!isset($_POST['guess'])) {
$message = "Welcome to the guessing machine!";
} elseif (!is_numeric($_POST['guess'])) { // is not numeric
$message = "I don't understand that response.";
} elseif ($_POST['guess'] ==
$num_to_guess) { // matches!
$message = "Well done!";
} elseif ($_POST['guess'] >
$num_to_guess) {
$message = $_POST['guess']." is too big! Try a smaller number.";
} elseif ($_POST['guess'] <
$num_to_guess) {
$message = $_POST['guess']." is too small! Try a larger number.";
} else { // some other condition
$message = "I am terribly confused.";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<p><strong>Guess number:</strong>
<?php echo $num_tries; ?></p>
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 40
<form action="<?php echo
$_SERVER['PHP_SELF']; ?>"
method="POST">
<p><label for="guess">Type your guess here:</label><br/>
<input type="text" id="guess" name="guess" /></p>
<input type="hidden" name="num_tries" value="<?php echo $num_tries; ?>"/>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>
 The counter should increment by 1 each time you access the form.
Q) Explain Redirecting User
Ans: When a server script communicates with a client, it must first send some headers that
provide information about the document to follow. PHP usually handles this for you
automatically, but you can choose to send your own header lines with PHP's
header() function
<html>
<head>
<title> Redirecting Page with Header</title>
</head>
<body>
<h1> Press the Submit to Redirect </h1>
<br>
<form action="redirectme.php" method="POST">
<input type="submit" name="submitbutton" value="Submit"/>
</form>
</body>
</html>
redirectme.php:
<?php
$submitbutton= $_POST['submitbutton']; if ($submitbutton)
{
header("Location: http://www.skuniversity.ac.in/");
}
?>
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 41
Q) Explain Sending Mail on Form Submission
Ans: The mail() function of PHP to send information like, suggestions/messages to specific
email address on form submission.
The mail() function with four parameters to send email as follows:
mail("$to", $subject, $message, $headers);
 $to variable is to store receiver's email id.
 $subject is a variable to store mail subject.
 $message is a variable to store user's message.
 $headers contains other email parameters like BCc, Cc etc.
Q) How to Upload a File in PHP
Ans: There is one global PHP variable called $_FILES. This variable is an associate double
dimension array and keeps all the information related to uploaded file. So if the value
assigned to the input's name attribute in uploading form was file, then PHP would create
following five variables –
$_FILES['file']['tmp_name'] - the uploaded file in the temporary directory on the web server.
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 42
$_FILES['file']['name'] - the actual name of the uploaded file.
$_FILES['file']['size'] - the size in bytes of the uploaded file.
$_FILES['file']['type'] - the MIME type of the uploaded file.
$_FILES['file']['error'] - the error code associated with this file upload.
Example:-
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="uploader.php" method="post" enctype="multipart/form-data"> Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>
</body>
</form>
uploader.php
<?php
$target_path = "e:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path))
{
echo "File uploaded successfully!";
}
else{
echo "Sorry, file not uploaded, please try again!";
}
?>
Q) Explain about Cookies and How to Set Cookies
A cookie is a small amount of data stored by the user's browser in compliance with a
request from a server or script. A single host can request that up to 20 cookies be stored by
a user's browser. Each cookie consists of a name, value, and expiration date, as well as host
and path information. The size of an individual cookie is limited to 4KB.
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 43
PHP Create/Retrieve a Cookie / modify the cookie
setcookie() - used to create cookie and modify the cookie, the global variable $_COOKIE
used to retrieve the cookie.
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>
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>
Q) What is Session? Explain, how to Start(set) and Destroy(unset) Sessions (or) Explain
about the sessions? (or) Explain about the Session Function Overview, Starting a Session,
Working with session variables, Destroying Sessions and Unsetting Variables?
Ans: A session is a way to store information (in variables) to be used across multiple page
(e.g. username, favorite color, etc).
Session Function Overview: Session functions provide a unique identifier to a user, which
can then be used to store and acquire information linked to that ID. When a visitor accesses
a session enabled page, either a new identifier is allocated or the user is re-associated with
one that was already established in a previous visit. Any variables that have been associated
with the session become available to your code through the $_SESSION superglobal.
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 44
$_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat";
Starting a Session :-
we must find the following line in your php.ini file and change the value from 0 to 1 (and
restart the web server):
session.auto_start = 0
A session is started with the session_start() function. The session_id() function enables you
to either set or retrieve a session ID.
Example :-
<?php
// Start the session session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat"; echo "Session variables are set.";
?>
</body>
</html>
printing session_id() :- session_id() used to set or retrieve a session ID.
Example program :-
<?php session_start();
echo "<p>Your session ID is ".session_id().".</p>";
?>
Working with Session Variables :-
When a session is started, we can store any number of variables in the $_SESSION
superglobal and then access them on any session-enabled page. The following program
shows that the accessing session variables.
<?php session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page echo "Favorite color is " .
$_SESSION["favcolor"] . ".<br>"; echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 45
Destroying Sessions and Unsetting Variables
To remove all global session variables and destroy the session, use session_unset() and
session_destroy():
Example :-
<?php session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables session_unset();
// destroy the session session_destroy();
?>
</body>
</html>
Q) Explain about Include and require
Ans: There are two PHP functions which can be used to included one PHP file into another
PHP file.
1. The include() Function
2. The require() Function
Theinclude() Function
The include() function takes all the text in a specified file and copies it into the file that uses
the include function. If there is any problem in loading a file then the include() function
generates a warning but the script will continue execution.
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
The require() Function
The require() function takes all the text in a specified file and copies it into the file that uses
the include function. If there is any problem in loading a file then the require() function
generates a fatal error and halt the execution of the script.
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 46
<html>
<body>
<?php require("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
Q) How to Validate Files
Ans: PHP provides many functions to help you to discover information about files on your
system. The file_exists() function. This function requires a string representation of an
absolute or relative path to a file, which might or might not be present. If the file is found,
the file_exists() function returns true; otherwise, it returns false:
if (file_exists('test.txt')) { echo "The file exists!";
}
The is_file() function requires the file path and returns a Boolean value: if (is_file('test.txt')) {
echo "test.txt is a file!";
}
The is_readable() function accepts the file path as a string and returns a Boolean value: if
(is_readable('test.txt')) {
echo "test.txt is readable";
}
The is_writable() function tells you whether you have the proper permission to write to a
file. As with is_readable(), the is_writable() function requires the file path and returns a
Boolean value. if (is_writable('test.txt')) {
echo "test.txt is writable";
}
The filesize() function attempts to determine and return its size in bytes. It returns false if it
encounters problems:
echo "The size of test.txt is ".filesize('test.txt');
Q) Explain Creating and Deleting Files
PHP Create File - fopen()
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:-
$myfile = fopen("testfile.txt", "w")
The most common modes are read (r), write (w), and append (a).
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 47
The fopen() function returns a file resource you use later to work with the open file. To open
a file for reading, you use the following:
$fp = fopen("test.txt", "r");
You use the following to open a file for writing:
$fp = fopen("test.txt", "w");
To open a file for appending (that is, to add data to the end of a file), you use this:
$fp = fopen("test.txt", "a"); Reading from Files
The fread() function accepts a file resource as an argument, as well as the number of bytes
you want to read. The fread() function returns the amount of data you requested, unless the
end of the file is reached first:
$chunk = fread($fp, 16); Reading a File with fread()
<?php
$filename = "test.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename"); 4: while (!feof($fp)) {
$chunk = fread($fp, 8);
echo $chunk."<br/>";
}
?>
Q) How to Create Directories in PHP
Ans: The mkdir() function enables you to create a directory. The mkdir() function requires a
string that represents the path to the directory you want to create and an octal number
integer that represents the mode you want to set for the directory. Remember, you specify
an octal (base 8) number using a leading 0; for example,
0777 or 0400.
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 48
The rmdir() function enables you to remove a directory from the filesystem if the process
running your script has the right to do so, and if the directory is empty. The rmdir() function
requires only a string representing the path to the directory you want to delete.
rmdir("testdir");
The opendir() function returns a directory handle unless the directory isn't present or
readable; in that case, it returns false:
$dh = opendir("testdir");
The readdir() returns only the names of its items, rather than full paths
Ex:
<?php
$dirname = ".";
$dh = opendir($dirname) or die("Couldn't open directory");
while (!(($file = readdir($dh)) === false ) )
{
if (is_dir("$dirname/$file"))
{
echo "(D) ";
}
echo $file."<br/>";
}
closedir($dh);
?>
Q) Explain about Creating of Images using PHP
Ans: Drawing a New Image
The basic PHP function used to create a new image is called ImageCreate(),The following
line creates a drawing area that is 300 pixels wide by 300 pixels high:
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 49
$myImage = ImageCreate(300,300);
The following examples define five such colors (black, white, red, green, and blue,
respectively), using the ImageColorAllocate() function and RGB values:
$black = ImageColorAllocate($myImage, 0, 0, 0);
$white = ImageColorAllocate($myImage, 255, 255, 255);
$red = ImageColorAllocate($myImage, 255, 0, 0);
$green = ImageColorAllocate($myImage, 0, 255, 0);
$blue = ImageColorAllocate($myImage, 0, 0, 255);
Drawing Shapes and Lines
Several PHP functions can assist you in drawing shapes and lines on your canvas:
. ImageEllipse() is used to draw an ellipse.
. ImageArc() is used to draw a partial ellipse.
. ImagePolygon() is used to draw a polygon.
. ImageRectangle() is used to draw a rectangle.
. ImageLine() is used to draw a line.
Getting Fancy with Pie Charts
Defining the canvas, defining the colors, and then drawing
and filling. We can use this same sequence of events to expand your scripts to create charts
and graphs, using either static or dynamic data for the data points.
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 50
 //draw a pie
 ImageFilledArc($myImage, 100, 100, 200, 150, 0, 90, $red, IMG_ARC_PIE);
 ImageFilledArc($myImage, 100, 100, 200, 150, 90, 180 , $green, IMG_ARC_PIE);
 ImageFilledArc($myImage, 100, 100, 200, 150, 180, 360 , $blue, IMG_ARC_PIE);
Image Creation from User Input
In addition to creating images from other images and drawing images on your own, you can
create images based on user input.
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 51
Q) Explain Importance of Good Database Design
Ans: A good database design is crucial for a high-performance application, thinking about
relationships and database efficiency-which includes ease of maintenance, minimizing
duplications, and avoiding inconsistencies-is part of normalization. So, before you even start
coding an application, spend a lot of time designing your database.
Q) Explain Types of Table Relationships
Ans: Table relationships come in several forms:
. One-to-one relationships
. One-to-many relationships
. Many-to-many relationships
One-to-One Relationships In a one-to-one relationship, a key appears only once in a related
table. for example, if each employee is assigned one computer within a company. Figure
shows the one-to-one relationship of employees to computers
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 52
One-to-Many Relationships
In a one-to-many relationship, keys from one table appear multiple times in a related table.
The example shown in Figure indicating a connection between employees and departments,
illustrates a one-to-many relationship
Many-to-Many Relationships
In a many-to-many relationship, the key value of one table can appear many times in a
related table. So far, it sounds like a one-to-many relationship the example of students and
classes: A student has an ID and a name. A class has an ID and a name.
A student usually takes more than one class at a time, and a class always contains more
than one student, as you can see in Figure.
Q) Explain Normalization
Ans: Normalization is the process of minimizing redundancy from a relation or set of
relations. Redundancy in relation may cause insertion, deletion and updation anomalies. So,
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 53
it helps to minimize the redundancy in relations. Normal forms are used to eliminate or
reduce redundancy in database tables.
First normal form (1NF) As per the rule of first normal form, an attribute (column) of a table
cannot hold multiple values. It should hold only atomic values.
Second normal form (2NF) A table is said to be in 2NF if both the following conditions hold:
 Table is in 1NF (First normal form)
 No non-prime attribute is dependent on the proper subset of any candidate key of
table.
 An attribute that is not part of any candidate key is known as non-prime attribute.
Third Normal form (3NF) A table design is said to be in 3NF if both the following conditions
hold: Table must be in 2NF Transitive functional dependency of non-prime attribute on any
super key should be removed.
An attribute that is not part of any candidate key is known as non-prime attribute.
In other words 3NF can be explained like this: A table is in 3NF if it is in 2NF and for each
functional dependency X-> Y at least one of the following conditions hold:
X is a super key of table
Y is a prime attribute of table
An attribute that is a part of one of the candidate keys is known as prime attribute.
Q) Explain MySQL Datatypes
Ans:- The type of fields (or columns) are also referred to as data types, after the type of data
you will be storing in those fields.
MySQL uses many different data types broken into three categories -
 Numeric
 Date and Time
 String Types.
Numeric Data Types The following list shows the common numeric data types and their
descriptions
INT - A normal-sized integer that can be signed or unsigned. You can specify a width of up to
11 digits.
TINYINT - A very small integer that can be signed or unsigned. You can specify a width of up
to 4 digits.
SMALLINT - A small integer that can be signed or unsigned. You can specify a width of up to
5 digits.
MEDIUMINT - A medium-sized integer that can be signed or unsigned. You can specify a
width of up to 9 digits.
BIGINT - A large integer that can be signed or unsigned. 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,
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 54
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 and Time Types The MySQL date and time datatypes 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.
DATETIME - 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.
TIMESTAMP - 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 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 -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.
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 - A BLOB or TEXT
column with a maximum length of 4294967295 characters. You do not specify a length with
LONGBLOB or LONGTEXT.
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 55
ENUM - An enumeration, which is a fancy term for list.
Q) Explain Some MySQL Commands (or) Explain DML,DQL,DCL Commands
Ans: Create Command:The generic table-creation syntax is
CREATE TABLE table_name (column_name column_type);
The table name is up to you, of course, but should be a name that reflects the usage of the
table.
CREATE TABLE grocery_inventory (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
item_name VARCHAR (50) NOT NULL, item_desc TEXT,
item_price FLOAT NOT NULL, curr_qty INT NOT NULL
);
Insert Command: The basic syntax of INSERT is
INSERT INTO table_name (column list) VALUES (column values);
Within the parenthetical list of values, you must enclose strings within quotation marks. The
SQL standard is single quotes, but MySQL enables the usage of either single or double
quotes.
Select Command: SELECT is the SQL command used to retrieve records from your tables.
This command syntax can be totally simple or very complicated, depending on which fields
you want to select, whether you want to select from multiple tables, and what conditions
you plan to impose
The most basic SELECT syntax looks like this:
SELECT expressions_and_columns FROM table_name
[WHERE some_condition_is_true]
[ORDER BY some_column [ASC | DESC]]
[LIMIT offset, rows]
Ordering SELECT Results If you want to order results a specific way, such as by date, ID,
name, and so on, specify your requirements using the ORDER BY clause. In the following
statement, the intention is a resultset ordered alphanumerically by item_name:
SELECT id, item_name, curr_qty FROM grocery_inventory ORDER BY item_name;
Success! The results are as follows:
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 56
The default sorting of ORDER BY results is ascending (ASC); strings sort from A to Z, integers
start at 0, and dates sort from oldest to newest. You can also specify a descending sort,
using DESC:
Using WHERE in Your Queries
This is when the WHERE clause comes in to play. From the example SELECT syntax, you see
that WHERE is used to specify a particular condition:
SELECT expressions_and_columns FROM table_name
[WHERE some_condition_is_true]
An example is to retrieve all the records for items with a quantity of 500:
SELECT * FROM grocery_inventory WHERE curr_qty = 500;
Here are the results:
String Comparison Using LIKE To matching strings within a WHERE clause by using = or !=,
but there's another useful operator for the WHERE clause when comparing strings: the LIKE
operator. This operator uses two characters as wildcards in pattern matching:
 % -Matches multiple characters
 _ -Matches exactly one character
SELECT * FROM grocery_inventory WHERE item_name LIKE 'A%';
Here are the results:
Update Command: UPDATE is the SQL command used to modify the contents of one or
more columns in an existing record or set of records. The most basic UPDATE syntax looks
like this:
UPDATE table_name
SET column1='new value', column2='new value2'
[WHERE some_condition_is_true]
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 57
Replace Command: Another method for modifying records is to use the REPLACE
command, which is remarkably similar to the INSERT command.
REPLACE INTO table_name (column list) VALUES (column values);
The REPLACE statement works like this: If the record you are inserting into the table
contains a primary key value that matches a record already in the table, the record in the
table is deleted and the new record inserted in its place.
REPLACE INTO grocery_inventory VALUES
(1, 'Granny Smith Apples', 'Sweet!', '0.50', 1000);
Delete Command: The basic DELETE syntax is as follows:
DELETE FROM table_name [WHERE some_condition_is_true] [LIMIT rows]
Q)Explain about Joins in MySQL
Ans: MySQL JOINS are used to retrieve data from multiple tables. A MySQL JOIN is
performed whenever two or more tables are joined in a SQL statement.
There are different types of MySQL joins:
1. MySQL INNER JOIN (or sometimes called simple join)
2. MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
3. MySQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
INNER JOIN (simple join) MySQL INNER JOINS return all rows from multiple tables where the
join condition is met.
The syntax for the INNER JOIN in MySQL is:
Visual Illustration:
In this visual diagram, the MySQL INNER JOIN returns the shaded area:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 58
The MySQL INNER JOIN would return the records where table1 and table2 intersect.
LEFT OUTER JOIN: This type of join returns all rows from the LEFT-hand table specified in
the ON condition and only those rows from the other table where the joined fields are equal
(join condition is met).
The syntax for the LEFT OUTER JOIN in MySQL is:
In some databases, the LEFT OUTER JOIN keywords are replaced with LEFT JOIN.
Visual Illustration
In this visual diagram, the MySQL LEFT OUTER JOIN returns the shaded area:
The MySQL LEFT OUTER JOIN would return the all records from table1 and only those
records from table2 that intersect with table1.
RIGHT OUTER JOIN This type of join returns all rows from the RIGHT-hand table specified
in the ON condition and only those rows from the other table where the joined fields are
equal (join condition is met).
Syntax The syntax for the RIGHT OUTER JOIN in MySQL is:
In some databases, the RIGHT OUTER JOIN keywords are replaced with RIGHT JOIN.
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 59
Visual Illustration
In this visual diagram, the MySQL RIGHT OUTER JOIN returns the shaded area:
The MySQL RIGHT OUTER JOIN would return the all records from table2 and only those
records from table1 that intersect with table2.
Q) Explain about Subqueries
Ans: A subquery is a SELECT statement that appears within another SQL statement. Such
queries can prove extremely useful because they often eliminate the need for JOIN queries,
and in the case of application programming, subqueries can eliminate the need for multiple
queries within loops
An example of the basic subquery syntax is shown here:
SELECT expressions_and_columns FROM table_name WHERE somecolumn = (SUBQUERY);
You can also use subqueries with UPDATE and DELETE statements, as shown here:
DELETE FROM table_name WHERE somecolumn = (SUBQUERY);
or
UPDATE table_name SET somecolumn = 'something' WHERE somecolumn = (SUBQUERY);
The following example uses a subquery to obtain records from users in the master_
name table who have an email address in the email table:
SELECT firstname, lastname FROM master_name
WHERE name_id IN (SELECT name_id FROM email);
The results of this query may look something like this:
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 60
Q) Explain Frequently Used String Functions in MySQL
Ans: MySQL's built-in string-related functions can be used several ways. You can use
functions in SELECT statements without specifying a table to retrieve a result of the
function. count characters in a string.
SELECT LENGTH('This is cool!');
The result is this: 13
SELECT CONCAT('My', 'S', 'QL');
This query results in the following:
RTRIM() and LTRIM() functions remove whitespace from either the right or left side of a
string:
SELECT RTRIM('stringstring ');
Stringstring
The LOCATE() function returns the position of the first occurrence of a given substring
within the target string. For example, you can look for a needle in a haystack:
SELECT LOCATE('needle', 'haystackneedlehaystack');
You should see this result: 9
The MySQL LCASE() and UCASE() functions transform a string into lowercase or uppercase:
SELECT LCASE('MYSQL');
Result: mysql
Repeat() string-manipulation function is which does just what it sounds like
SELECT REPEAT("bowwow", 4);
You should see this result: bowwowbowwowbowwowbowwow |
The REPLACE() function replaces all occurrences of a given string with another string:
SELECT REPLACE('bowwowbowwowbowwowbowwow', 'wow', 'WOW');
Result: bowWOWbowWOWbowWOWbowWOW
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 61
Q) How to Use Data and Time Functions in MySQL
Ans:- MySQL's built-in date-related functions in SELECT statements, with or without
specifying a table, to retrieve a result of the function Working with Days
The DAYOFWEEK() and WEEKDAY() functions do similar things with slightly different
results. 2 and 0 for Monday
The DAYOFMONTH() and DAYOFYEAR() functions are more straightforward, with only
one result and a range that starts at 1 and ends at 31 for DAYOFMONTH() and 366 for
DAYOFYEAR().
Working with Months and Years MONTH() and MONTHNAME() return the number of the
month in a year and the name of the month for a given date. For example:
SELECT MONTH('2012-01-09'), MONTHNAME('2012-01-09');
1 January
Working with Weeks: Working with Weeks there can be 53 weeks in a year if Sunday is
the first day of the week and December hasn't ended.
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 62
Working with Hours, Minutes, and Seconds There are functions to find the hours, minutes,
and seconds from that string.These functions are called HOUR(), MINUTE(), and SECOND().
HOUR() returns the hour in a given time, which is between 0 and 23. The range for
MINUTE() and SECOND() is 0 to 59.
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;
Q) What is Transaction?
Ans: A transaction is a sequential group of database manipulation operations, which is
performed as if it were one single work unit. In other words, a transaction will never be
complete unless each individual operation within the group is successful. If any operation
within the transaction fails, the entire transaction will fail.
Output:
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 63
Properties of Transactions
Transactions have the following four standard properties, usually referred to by the
acronym ACID -
Atomicity - This ensures that all operations within the work unit are completed
successfully; otherwise, the transaction is aborted at the point of failure and
previous operations are rolled back to their former state.
Consistency - This ensures that the database properly changes states upon a
successfully committed transaction.
Isolation - This enables transactions to operate independently on and transparent to
each other.
Durability - This ensures that the result or effect of a committed transaction persists
in case of a system failure.
COMMIT and ROLLBACK These two keywords Commit and Rollback are mainly used for
MySQL Transactions. When a successful transaction is completed, the COMMIT command
should be issued so that the changes to all involved tables will take effect. If a failure occurs,
a ROLLBACK command should be issued to return every table referenced in the transaction
to its previous state.
Q) What are Stored Procedures
Ans: a stored procedure is a procedure in SQL that is stored in the database server rather
than the web server By using stored procedures in code point to performance and
maintenance as key reasons for doing so:
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 //
The name of the stored procedure is sp1:
CREATE PROCEDURE sp1 () SELECT * FROM testSP WHERE date_added BETWEEN
DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() //
To call the stored procedure, use the CALL command:
CALL sp1 () //
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 64
Q) Explain about mysql() Vs mysqli() Functions
Ans: There are too many differences between these PHP database extensions. These
differences are based on some factors like performance, library functions, features,
benefits, and others.
MySQL MySQLi
MySQL extension added in PHP version
2.0. and deprecated as of PHP 5.5.0.
Does not support prepared statements.
MySQL provides the procedural
Interface
MySQL extension does not support
stored procedure
MySQL extension lags in security and
other special features, comparatively.
Transactions are handled by SQL queries
only.
Extension directory: ext/mysql.
MySQLi extension added in PHP 5.5 and
will work on MySQL 4.1.3 or above.
MySQLi supports prepared statements.
MySQLi provides both procedural and
object-oriented interface.
MySQLi supports store procedure.
MySQLi extension is with enhanced
security and improved debugging.
MySQLi supports transactions through
API.
Extension directory: ext/mysqli.
Q) How to Connect MySQL with PHP
Ans: Making a Connection
The basic syntax for a connection to MySQL is as follows:
$mysqli = mysqli_connect("hostname", "username", "password", "database");
The value of $mysqli is the result of the function and is used in later functions for
communicating with MySQL.
With sample values inserted, the connection code looks like this:
$mysqli = mysqli_connect("localhost", "joeuser", "somepass", "testDB");
A Simple Connection Script
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 65
Executing Queries: The mysqli_query() function in PHP is used to send your SQL query to
MySQL. The mysqli_query function returns a value of true or false, and this value is checked
in the if...else statement If the value of $res is true, a success message is printed to the
screen. If you access MySQL through the command-line interface to verify the creation of
the table
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = "INSERT INTO Persons (PersonID,LastName,FirstName,Address,City) VALUES ('7', 'sdf',
'sdfad', 'knl', 'beng')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysqli_close($conn);
?>
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 66
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = "select * from Persons";
$res=mysqli_query($conn,$sql);
if($res){
$num_of_rows=mysqli_num_rows($res);
printf("Result Set %d rows n",$num_of_rows);
}
else {
printf("Could Not Retrive",mysqli_error($mysqli));
}
mysqli_free_result($res);
mysqli_close($conn);
?>
Q) Create Online Address Book
Ans: creating a manageable online address book. You learn how to create the relevant
database tables, as well as the forms and scripts for adding, deleting, and viewing database
records.
These basic concepts are the foundations of developing any application that uses CRUD
functionality (create, read, update, delete), which is precisely what a lot of web-based
applications.
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 67
Planning and Creating the Database Tables
In an online address book, a set of related tables helps alleviate the redundancy and
repetition of information and allows you to display all information in a unified view.
Creating a Menu
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 68
Creating the Record-Addition Mechanism
s4s
PHP, MySQL & WORDPRESS
Prepared By
D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 69
Viewing Records
Showing Records:
s4s
DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL
B.Sc (Computer Science) – Cluster C1 Page 70
Q) What is WordPress? Explain its Features
Ans: WordPress is an open source Content Management System (CMS), which allows the
users to build dynamic websites and blogs. WordPress is the most popular blogging system
on the web and allows updating, customizing and managing the website from its back-end
CMS and components.
Features:
 User Management: It allows managing the user information such as changing the
role of the users to (subscriber, contributor, author, editor or administrator), create
or delete the user, change the password and user information. The main role of the
user manager is Authentication.
 Media Management: It is the tool for managing the media files and folder, in
which you can easily upload, organize and manage the media files on your website.
 Theme System: It allows modifying the site view and functionality. It includes
images, stylesheet, template files and custom pages.
 Extend with Plugins: Several plugins are available which provides custom functions
and features according to the users need.
 Search Engine Optimization: It provides several search engine optimization (SEO)
tools which makes on-site SEO simple.
 Multilingual: It allows translating the entire content into the language preferred by
the user.
 Importers: It allows importing data in the form of posts. It imports custom files,
comments, post pages and tags.
Q) Explain about WAMP and XAMP(bitnami) Servers.
Ans:
1. WampServer is a Windows web development environment. It allows you to create web
applications with Apache2, PHP and a MySQL database. Alongside, PhpMyAdmin allows you
to manage easily your databases.
Using wampserver
 The "www" directory will be automatically created (usually c:wampwww)
 Create a subdirectory in "www" and put your PHP files inside.
 Click on the "localhost" link in the WampSever menu or open your internet browser
and go to the URL : http://localhost
s4s
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress
SULTHAN's PHP, MySQL & wordpress

More Related Content

What's hot

Btpsec Sample Penetration Test Report
Btpsec Sample Penetration Test ReportBtpsec Sample Penetration Test Report
Btpsec Sample Penetration Test Reportbtpsec
 
La sécurité informatique
La sécurité informatiqueLa sécurité informatique
La sécurité informatiqueSaber Ferjani
 
Metasploit
MetasploitMetasploit
Metasploithenelpj
 
VMware vSphere 6.0 - Troubleshooting Training - Day 1
VMware vSphere 6.0 - Troubleshooting Training - Day 1VMware vSphere 6.0 - Troubleshooting Training - Day 1
VMware vSphere 6.0 - Troubleshooting Training - Day 1Sanjeev Kumar
 
La sécurité informatique expliquée aux salariés
La sécurité informatique expliquée aux salariésLa sécurité informatique expliquée aux salariés
La sécurité informatique expliquée aux salariésNRC
 
Log4Shell Case Study - Suricon2022.pdf
Log4Shell Case Study - Suricon2022.pdfLog4Shell Case Study - Suricon2022.pdf
Log4Shell Case Study - Suricon2022.pdfBrandon DeVault
 
Virtualization Vs. Containers
Virtualization Vs. ContainersVirtualization Vs. Containers
Virtualization Vs. Containersactualtechmedia
 
VAPT PRESENTATION full.pptx
VAPT PRESENTATION full.pptxVAPT PRESENTATION full.pptx
VAPT PRESENTATION full.pptxDARSHANBHAVSAR14
 
Radware - WAF (Web Application Firewall)
Radware - WAF (Web Application Firewall)Radware - WAF (Web Application Firewall)
Radware - WAF (Web Application Firewall)Deivid Toledo
 
F5 - BigIP ASM introduction
F5 - BigIP ASM introductionF5 - BigIP ASM introduction
F5 - BigIP ASM introductionJimmy Saigon
 
L’iam : au-delà des idées reçues, les clés de la gestion des identités et des...
L’iam : au-delà des idées reçues, les clés de la gestion des identités et des...L’iam : au-delà des idées reçues, les clés de la gestion des identités et des...
L’iam : au-delà des idées reçues, les clés de la gestion des identités et des...Identity Days
 
VMware vSphere technical presentation
VMware vSphere technical presentationVMware vSphere technical presentation
VMware vSphere technical presentationaleyeldean
 
20 common security vulnerabilities and misconfiguration in Azure
20 common security vulnerabilities and misconfiguration in Azure20 common security vulnerabilities and misconfiguration in Azure
20 common security vulnerabilities and misconfiguration in AzureCheah Eng Soon
 

What's hot (20)

Port Scanning
Port ScanningPort Scanning
Port Scanning
 
Btpsec Sample Penetration Test Report
Btpsec Sample Penetration Test ReportBtpsec Sample Penetration Test Report
Btpsec Sample Penetration Test Report
 
La sécurité informatique
La sécurité informatiqueLa sécurité informatique
La sécurité informatique
 
Metasploit
MetasploitMetasploit
Metasploit
 
Windows Server 2012 Hyper-V Networking Evolved
Windows Server 2012 Hyper-V Networking Evolved Windows Server 2012 Hyper-V Networking Evolved
Windows Server 2012 Hyper-V Networking Evolved
 
VMware vSphere 6.0 - Troubleshooting Training - Day 1
VMware vSphere 6.0 - Troubleshooting Training - Day 1VMware vSphere 6.0 - Troubleshooting Training - Day 1
VMware vSphere 6.0 - Troubleshooting Training - Day 1
 
La sécurité informatique expliquée aux salariés
La sécurité informatique expliquée aux salariésLa sécurité informatique expliquée aux salariés
La sécurité informatique expliquée aux salariés
 
Log4Shell Case Study - Suricon2022.pdf
Log4Shell Case Study - Suricon2022.pdfLog4Shell Case Study - Suricon2022.pdf
Log4Shell Case Study - Suricon2022.pdf
 
VMware Presentation
VMware PresentationVMware Presentation
VMware Presentation
 
Virtualization Vs. Containers
Virtualization Vs. ContainersVirtualization Vs. Containers
Virtualization Vs. Containers
 
F5 Web Application Security
F5 Web Application SecurityF5 Web Application Security
F5 Web Application Security
 
Security testing
Security testingSecurity testing
Security testing
 
VAPT PRESENTATION full.pptx
VAPT PRESENTATION full.pptxVAPT PRESENTATION full.pptx
VAPT PRESENTATION full.pptx
 
VMware vSphere
VMware vSphereVMware vSphere
VMware vSphere
 
Radware - WAF (Web Application Firewall)
Radware - WAF (Web Application Firewall)Radware - WAF (Web Application Firewall)
Radware - WAF (Web Application Firewall)
 
F5 - BigIP ASM introduction
F5 - BigIP ASM introductionF5 - BigIP ASM introduction
F5 - BigIP ASM introduction
 
L’iam : au-delà des idées reçues, les clés de la gestion des identités et des...
L’iam : au-delà des idées reçues, les clés de la gestion des identités et des...L’iam : au-delà des idées reçues, les clés de la gestion des identités et des...
L’iam : au-delà des idées reçues, les clés de la gestion des identités et des...
 
VMware vSphere technical presentation
VMware vSphere technical presentationVMware vSphere technical presentation
VMware vSphere technical presentation
 
OpenStack Framework Introduction
OpenStack Framework IntroductionOpenStack Framework Introduction
OpenStack Framework Introduction
 
20 common security vulnerabilities and misconfiguration in Azure
20 common security vulnerabilities and misconfiguration in Azure20 common security vulnerabilities and misconfiguration in Azure
20 common security vulnerabilities and misconfiguration in Azure
 

Similar to SULTHAN's PHP, MySQL & wordpress

My First 100 days with a MySQL DBMS (WP)
My First 100 days with a MySQL DBMS (WP)My First 100 days with a MySQL DBMS (WP)
My First 100 days with a MySQL DBMS (WP)Gustavo Rene Antunez
 
Getting started with my sql
Getting started with my sqlGetting started with my sql
Getting started with my sqlWeb Sky
 
Mysqlppt3510
Mysqlppt3510Mysqlppt3510
Mysqlppt3510Anuja Lad
 
My sql università di enna a.a. 2005-06
My sql   università di enna a.a. 2005-06My sql   università di enna a.a. 2005-06
My sql università di enna a.a. 2005-06YUCHENG HU
 
Based on the materials for this week, create your own unique Datab.docx
Based on the materials for this week, create your own unique Datab.docxBased on the materials for this week, create your own unique Datab.docx
Based on the materials for this week, create your own unique Datab.docxJASS44
 
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdfCompare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdfarihantplastictanksh
 
Connecting to my sql using PHP
Connecting to my sql using PHPConnecting to my sql using PHP
Connecting to my sql using PHPNisa Soomro
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptxKulbir4
 
Mysql Replication Excerpt 5.1 En
Mysql Replication Excerpt 5.1 EnMysql Replication Excerpt 5.1 En
Mysql Replication Excerpt 5.1 Enliufabin 66688
 
My sql technical reference manual
My sql technical reference manualMy sql technical reference manual
My sql technical reference manualMir Majid
 

Similar to SULTHAN's PHP, MySQL & wordpress (20)

My First 100 days with a MySQL DBMS (WP)
My First 100 days with a MySQL DBMS (WP)My First 100 days with a MySQL DBMS (WP)
My First 100 days with a MySQL DBMS (WP)
 
Mysql ppt
Mysql pptMysql ppt
Mysql ppt
 
Getting started with my sql
Getting started with my sqlGetting started with my sql
Getting started with my sql
 
Mysql tutorial
Mysql tutorialMysql tutorial
Mysql tutorial
 
Mysql tutorial 5257
Mysql tutorial 5257Mysql tutorial 5257
Mysql tutorial 5257
 
My sql basic
My sql basicMy sql basic
My sql basic
 
Mysqlppt3510
Mysqlppt3510Mysqlppt3510
Mysqlppt3510
 
Mysqlppt3510
Mysqlppt3510Mysqlppt3510
Mysqlppt3510
 
My sql università di enna a.a. 2005-06
My sql   università di enna a.a. 2005-06My sql   università di enna a.a. 2005-06
My sql università di enna a.a. 2005-06
 
Sql installation
Sql installationSql installation
Sql installation
 
Slides
SlidesSlides
Slides
 
Based on the materials for this week, create your own unique Datab.docx
Based on the materials for this week, create your own unique Datab.docxBased on the materials for this week, create your own unique Datab.docx
Based on the materials for this week, create your own unique Datab.docx
 
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdfCompare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
 
Lovely
LovelyLovely
Lovely
 
Introduction to Mysql
Introduction to MysqlIntroduction to Mysql
Introduction to Mysql
 
Connecting to my sql using PHP
Connecting to my sql using PHPConnecting to my sql using PHP
Connecting to my sql using PHP
 
Mysql
MysqlMysql
Mysql
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
 
Mysql Replication Excerpt 5.1 En
Mysql Replication Excerpt 5.1 EnMysql Replication Excerpt 5.1 En
Mysql Replication Excerpt 5.1 En
 
My sql technical reference manual
My sql technical reference manualMy sql technical reference manual
My sql technical reference manual
 

More from SULTHAN BASHA

Sulthan's_JAVA_Material_for_B.Sc-CS.pdf
Sulthan's_JAVA_Material_for_B.Sc-CS.pdfSulthan's_JAVA_Material_for_B.Sc-CS.pdf
Sulthan's_JAVA_Material_for_B.Sc-CS.pdfSULTHAN BASHA
 
Sulthan's DBMS for_Computer_Science
Sulthan's DBMS for_Computer_ScienceSulthan's DBMS for_Computer_Science
Sulthan's DBMS for_Computer_ScienceSULTHAN BASHA
 
SULTHAN's - PHP MySQL programs
SULTHAN's - PHP MySQL programsSULTHAN's - PHP MySQL programs
SULTHAN's - PHP MySQL programsSULTHAN BASHA
 
SULTHAN's ICT-2 for UG courses
SULTHAN's ICT-2 for UG coursesSULTHAN's ICT-2 for UG courses
SULTHAN's ICT-2 for UG coursesSULTHAN BASHA
 
SULTHAN's - Data Structures
SULTHAN's - Data StructuresSULTHAN's - Data Structures
SULTHAN's - Data StructuresSULTHAN BASHA
 
SULTHAN's - ICT-1 for U.G courses in India
SULTHAN's - ICT-1 for U.G courses in IndiaSULTHAN's - ICT-1 for U.G courses in India
SULTHAN's - ICT-1 for U.G courses in IndiaSULTHAN BASHA
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN BASHA
 

More from SULTHAN BASHA (7)

Sulthan's_JAVA_Material_for_B.Sc-CS.pdf
Sulthan's_JAVA_Material_for_B.Sc-CS.pdfSulthan's_JAVA_Material_for_B.Sc-CS.pdf
Sulthan's_JAVA_Material_for_B.Sc-CS.pdf
 
Sulthan's DBMS for_Computer_Science
Sulthan's DBMS for_Computer_ScienceSulthan's DBMS for_Computer_Science
Sulthan's DBMS for_Computer_Science
 
SULTHAN's - PHP MySQL programs
SULTHAN's - PHP MySQL programsSULTHAN's - PHP MySQL programs
SULTHAN's - PHP MySQL programs
 
SULTHAN's ICT-2 for UG courses
SULTHAN's ICT-2 for UG coursesSULTHAN's ICT-2 for UG courses
SULTHAN's ICT-2 for UG courses
 
SULTHAN's - Data Structures
SULTHAN's - Data StructuresSULTHAN's - Data Structures
SULTHAN's - Data Structures
 
SULTHAN's - ICT-1 for U.G courses in India
SULTHAN's - ICT-1 for U.G courses in IndiaSULTHAN's - ICT-1 for U.G courses in India
SULTHAN's - ICT-1 for U.G courses in India
 
SULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notesSULTHAN's - C Programming Language notes
SULTHAN's - C Programming Language notes
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 

SULTHAN's PHP, MySQL & wordpress

  • 1. PHP, MySQL & WORDPRESSA study material for B.Sc (Computer Science) With this book we can learn how to install PHP, APACHE and MySQL or XAMPP. And developing web pages using PHP. Maintaining database with MySQL and combining PHP code with MySQL. And can learn Wordpress to create websites. D.SULTHAN BASHA M.Sc s4s
  • 2. s4s
  • 3. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 1 Q) What is MySQL? Ans: MySQL is the most popular Open Source Relational SQL Database Management System. MySQL is one of the best RDBMS being used for developing various web-based software applications. MySQL is developed, marketed and supported by MySQL AB. Q) Explain Current Versions and Features of MYSQL Ans: MySQL supports the current version MySQL 5.7. This version release notes contains the all the previous decorticated functions and newly added features. The following features are there in current version of MySQL 5.7. 1. Performance & Scalability: Improved Innovative DB scalability and temporary table performance, enabling faster online and bulk load operations, and more. 2. JSON (Java Script Object Notation) Support: With the newly added JSON support in MySQL, you can now combine the flexibility of NoSQL with the strength of a relational database. 3. Replication improvements for increased availability and performance. They include multi- source replication, multi-threaded slave enhancements 4. Performance Schema delivering much better and new monitoring capabilities, reduced the footprint and overhead, and significantly improved ease of use with the new Schema. 5. Security: Fulfilling "secure by default" requirements and many new MySQL 5.7 features will help users keep their database secure. 6. Optimizer: We have rewritten large parts of the parser, optimizer, and cost model. This has improved maintainability, expendability, and performance. Q) How to Get MySQL? Ans: MySQL AB was the name of the company that developed, maintained, and distributed the MySQL database server; through a series of acquisitions (Sun Microsystems purchased MySQL AB, and Oracle Corporation purchased Sun Microsystems), database giant Oracle now owns MySQL. However, the MySQL Community Edition of the software remains open source, is supported by open source developers, and is freely available on the MySQL website at http://www.mysql.com/. Binary distributions for all platforms, installer packages for Mac OS X, and RPMs and source code files for Linux/UNIX platforms are all available. Q) How to Install and Configure MySQL? Ans: MySQL can be installed and configured with different platforms. 1. MySQL Installation on Linux/UNIX: The process of installing MySQL on Linux/UNIX is straightforward, whether you use RPMs or install the binaries. If you are installing from RPMs, there are platform specific RPMs such as those for generic Linux running on different processor types, such as x86 32- and 64-bit. To perform a minimal installation from RPMs, type the following at your prompt: # rpm -i MySQL-server-VERSION.i386.rpm MySQL-client-VERSION.i386.rpm Another painless (and very common) installation method is to install MySQL from a binary distribution. This method requires the gunzip and tar utilities to uncompress and s4s
  • 4. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 2 unpack the distribution, and also requires the ability to create groups and users on the system. The first series of commands in the binary distribution installation process has you adding a group and a user and unpacking the distribution, as follows: # groupadd mysql # useradd -r -g mysql mysql # cd /usr/local # tar zxvf /path/to/mysql-VERSION-PLATFORM.tar.gz 2. MySQL Installation on Windows: The MySQL installation process on Windows uses a standard Microsoft Windows Installer (MSI) file to walk you through the installation and configuration of MySQL on your Windows XP, Windows Server 2003, Windows Vista, or Windows 7 machine. Go to the MySQL downloads page at http://dev.mysql.com/downloads/mysql/ 5.5.html and select the Windows option from the drop-down menu. Download the Windows MSI Installer file for your system, either 32- or 64-bit. * The Security Options configuration screen is the most important screen of all. As shown in Figure 2.10, use this configuration screen to set a root password. Enter the password twice to confirm it. s4s
  • 5. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 3 Q) How to Troubleshoot MySQL Installation? Ans: The following are just a few of the common installation problems:  On Linux/UNIX and Mac OS X, incorrect permissions do not allow you to start the MySQL daemon. If this is the case, be sure that you have changed owners and groups to match those indicated in the installation instructions.  If you see the message Access denied when connecting to MySQL, be sure that you are using the correct username and password.  If you see the message Can't connect to server, make sure that the MySQL daemon is running. Q) Explain about Basic Security Guidelines in MySQL? Ans: Regardless of whether you are running MySQL on Windows, Linux/UNIX, or Mac OS X, and no matter whether you administer your own server or use a system provided to you by your Internet service provider. Starting MySQL: Securing MySQL begins with the server start-up procedure. If you are not the administrator of the server, you cannot change this, but you can certainly check it out and report vulnerabilities to your Internet service provider. Securing Your MySQL Connection: We can connect to the MySQL monitor (command-line interface) or other MySQL applications in several different ways, each of which has its own security risks. If your MySQL installation is on your own workstation.  If MySQL is installed on your workstation, your biggest security concern is leaving your workstation unattended with your MySQL monitor or MySQL GUI administration tool up and running.  If MySQL is installed on a server outside your network, the security of the connection should be of some concern. As with any transmission of data over the Internet, data can be intercepted. If the transmission is unencrypted, the person who intercepted the data can piece it together and use the information. By using SSH (Secure Shell) connection mode we can avoid this issues. Q) Explain about MySQL Privilege System (or) How to add users in MySQL? Ans: There are several privilege-related tables in the mysql database, such as the following:  columns_priv-Defines user privileges for specific fields within a table  db-Defines the permissions for all databases on the server  host-Defines the acceptable hosts that can connect to a specific database  procs_priv-Defines user privileges for stored routines  tables_priv-Defines user privileges for specific tables within a database  user-Defines the command privileges for a specific user Understanding the Two-Step Authentication Process: MySQL checks three things during the authentication process. The actions associated with above three things are performed in two steps: s4s
  • 6. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 4 Step: 1. MySQL looks at the host you are connecting from and the username and password pair you are using. If correct id, password then MySQL moves to the second step. Step: 2. For whichever SQL command you are attempting to use, MySQL verifies that your user has permissions to perform that action for that database, table, and field. If step 1 fails, you see an error about it and you cannot continue on to step 2. For example, suppose that you are connecting to MySQL with a username of joe and a password of abc123 and you want to access a database called myDB. You will receive an error message if any of those connection variables is incorrect for any of the following reasons:  Your password is incorrect.  Username joe doesn't exist.  User joe can't connect from localhost.  User joe can connect from localhost but cannot use the myDB database. If user joe with a password of abc123 is allowed to connect from localhost to the myDB database, MySQL checks the actions that joe can perform in step 2 of the process. Adding Users to MySQL: The simplest method for adding new users is the GRANT command. The simple syntax of the GRANT command is shown here: Following are some of the common privileges you can grant  ALL-Gives the user all common privileges.  ALTER-User can alter (modify) tables, columns, and indexes.  CREATE-User can create databases and tables.  DELETE-User can delete records from tables.  DROP-User can drop (delete) tables and databases.  FILE-User can read and write files; this privilege is used to import or dump data.  INDEX-User can add or delete indexes.  INSERT-User can add records to tables.  PROCESS-User can view and stop system processes; only trusted users should be able to do this.  RELOAD-User can issue FLUSH statements; only trusted users should be able to do this.  SELECT-User can select records from tables.  SHUTDOWN-User can shut down the MySQL server; only trusted users should be able to do this.  UPDATE-User can update (modify) records in tables. If, for instance, you want to create a user called john with a password of 99hjc!5, with SELECT and INSERT privileges on all tables in the database called myDB, and you want this user to be able to connect from any host, use this command: GRANT privileges ON databasename.tablename TO username@host IDENTIFIED BY "password"; s4s
  • 7. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 5 Note the use of two wildcards: * and %. These wildcards replace values. In this example, * replaces the entire list of tables, and % replaces a list of all hosts in the known world-a very long list indeed. Here's another example of adding a user with the GRANT command, this time to add a user called jane with a password of 45sdg11, with ALL privileges on a table called employees Removing User Privileges: Removing privileges is as simple as adding them; instead of the GRANT command, you use REVOKE. The REVOKE command syntax is as follows: Q) Explain Apache Web Server and its Current Version and Features Ans: Apache is the actual web server application that processes and delivers web content to a computer. Apache is the most popular web server online, powering nearly 54% of all websites. The Apache HTTPD server website at http://httpd.apache.org shows announcements for releases of the Apache 2.0.x, Apache 2.2.x, and Apache 2.4.x versions. As you can understand by the version numbers, Apache 2.0.x is the oldest of the three versions. The Apache Software Foundation maintains all three versions, but the features in Apache 2.4.x include the latest and greatest. Apache HTTP Server version 2.4 provides the following notable features:  The event Multi-Processing Module (MPM) and integrated proxy module support for the FastCGI protocol allow the server to serve more concurrent requests.  Improvements to asynchronous read and write handling.  Embedded scripting. Installing Apache on Linux/UNIX This section explains how to install a fresh build of Apache 2.4.1 on Linux/UNIX. The general steps necessary to successfully install Apache from source are as follows: 1. Download the software. 2. Run the configuration script. 3. Compile the code and install it GRANT SELECT, INSERT ON myDB.* TO john@"%" IDENTIFIED BY "99hjc!5"; GRANT ALL ON myCompany.employees TO jane@janescomputer.company.com IDENTIFIED BY "45sdg11"; REVOKE privileges ON databasename.tablename FROM username@hostname; s4s
  • 8. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 6 Installing Apache on Windows: Apache 2.2 runs on most Windows platforms and offers increased performance and stability over earlier versions for Windows. You can build Apache from source, but because not many Windows users have compilers, this section deals with the MSI installer version. Q) Explain Apache Configuration File Structure Ans: Apache Configuration File Structure: Apache keeps all its configuration information in text files. The main file is httpd.conf. This file contains directives and containers that enable you to customize your Apache installation. Directives configure specific settings of Apache, such as authorization, performance, and network parameters. Containers specify the context to which those settings refer. The Apache documentation for directives typically follows this model: . Description-This entry provides a brief description of the directive. . Syntax-This entry explains the format of the directive options. Compulsory parameters appear in italics, and optional parameters appear in italics and brackets. . Default-If the directive has a default value, it appears here. . Context-This entry details the containers or sections in which the directive can appear. The next section explains containers. The possible values are server config, virtual host, irectory, and .htaccess. These are the default Apache containers: . <VirtualHost>-A VirtualHost directive specifies a virtual server. Apache enables you to host different websites with a single Apache installation. . <Directory>, <DirectoryMatch>-These containers allow directives to apply to a certain directory or group of directories in the filesystem. Directory containers take a directory or directory pattern argument. . <Location>, <LocationMatch>-These containers allow directives to apply to certain requested URLs or URL patterns. . <Files>, <FilesMatch>-Similar to the Directory and Location containers, Files sections allow directives to apply to certain files or file patterns. Q) Explain Apache Log Files and Apache Related Commands Ans: Apache includes two log files by default. The access_log file is for tracking client requests. The error_log file is for recording important events, such as errors or server restarts. These files don't exist until you start Apache the first time. The names of the files are access.log and error.log in Windows platforms. The access_log File When a client requests a file from the server, Apache records several parameters associated with the request, including the IP address of the client, the document requested, the HTTP status code, and the current time s4s
  • 9. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 7 The error_log File The error_log file includes error messages, startup messages, and any other significant events in the life cycle of the server. This is the first place to look when you have a problem with Apache. On Windows, you can signal Apache using the httpd.exe executable. Some commands are listed here: . httpd.exe -k restart-Tells Apache to restart . httpd.exe -k graceful-Tells Apache to do a graceful restart . httpd.exe -k stop-Tells Apache to stop Q) Explain Apache Installation Troubleshoot Ans:- Already an Existing Web Server If a server is already running on the machine and is listening to the same IP address and port combination, Apache cannot start successfully. You will get an entry in the error log file indicating that Apache cannot bind to the port No Permission to Bind to Port You will get an error if you do not have administrator permissions and you try to bind to a privileged port (between 0 and 1024): To solve this problem, you must either log on as the administrator before starting Apache or change the port number; 8080 is a commonly used nonprivileged port Access Denied You might not be able to start Apache if you do not have permission to read the configuration files or to write to the log files. Q) Explain about the advantages and disadvantages of PHP? Or Explain about the features of PHP? Ans: Introduction: PHP stands for Hypertext Preprocessor. PHP is a powerful and widely- used open source server-side scripting language to write dynamically generated web pages. PHP scripts are executed on the server and the result is sent to the browser as plain HTML. [crit] (13)Permission denied: make_sock: could not bind to address 10.0.0.2:80 [alert] no listening sockets available, shutting down s4s
  • 10. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 8 PHP can be integrated with the number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. PHP can be embedded within a normal HTML web pages. That means inside your HTML documents you'll have PHP statements like this: What is PHP  PHP is an acronym for "PHP: Hypertext Preprocessor"  PHP is a widely-used, open source scripting language  PHP scripts are executed on the server  PHP is free to download and use What is a PHP File?  PHP files can contain text, HTML, CSS, JavaScript, and PHP code  PHP code are executed on the server, and the result is returned to the browser as plain HTML  PHP files have extension ".php" What Can PHP Do?  PHP can generate dynamic page content  PHP can create, open, read, write, delete, and close files on the server  PHP can collect form data  PHP can send and receive cookies  PHP can add, delete, modify data in your database  PHP can be used to control user-access  PHP can encrypt data Why PHP?  PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)  PHP is compatible with almost all servers used today (Apache, IIS, etc.)  PHP supports a wide range of databases  PHP is free. Download it from the official PHP resource: www.php.net  PHP is easy to learn and runs efficiently on the server side Advantages of PHP 1. Open source: It is developed and maintained by a large group of PHP developers, this will helps in creating a support community, abundant extension library. 2. Speed: It is relative fast since it uses much system resource. 3. Easy to use: It uses C like syntax, so for those who are familiar with C, it's very easy for them to pick up and it is very easy to create website scripts. 4. Stable: Since it is maintained by many developers, so when bugs are found, it can be quickly fixed. s4s
  • 11. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 9 5. Powerful library support: we can easily find functional modules you need such as PDF, Graph etc. 6. Built-in database connection modules: You can connect to database easily using PHP, since many websites are data/content driven, so we will use database frequently, this will largely reduce the development time of web apps. 7. Can be run on many platforms, including Windows, Linux and Mac, it's easy for users to find hosting service providers. Disadvantages of PHP 1. Security: Since it is open sourced, so all people can see the source code, if there are bugs in the source code, it can be used by people to explore the weakness of PHP. 2. Not suitable for large applications: Hard to maintain since it is not very modular. 3. Weak type: Implicit conversion may surprise unwary programmers and lead to unexpected bugs. For example, the strings "1000" and "1e3" compare equal because they are implicitly cast to floating point numbers. Q) Explain Installation and Configuration of PHP in Linux and Windows Ans: Installing and Configuring PHP on Linux: To download the PHP distribution files, go to the home of PHP, http://www.php.net/, and follow the link to the Downloads section. Grab the latest version of the source code-for this example, we are using 5.4.0. Your distribution will be named something similar to php-VERSION.tar.gz, where VERSION is the most recent release number. This archive will be a compressed tar file, so you need to unpack it: Integrating PHP with Apache on Linux/UNIX To ensure that PHP and Apache get along with one another, you need to check for and potentially add-a few items to the httpd.conf configuration file Add the following line to that section: This statement ensures that the PHP engine will parse files that end with the .php extension. PHP is now part of the Apache web server. Installing and Configuring PHP on Windows: Installing PHP on Windows requires nothing more than downloading the distribution file. To download the PHP distribution files, go to the home of PHP on Windows, http://windows.php.net/, and follow the link to the Downloads page After the file downloads to your system, double-click it to launch your unzipping software. The distribution is packed up with relative pathnames already in place, so extract the files to a new directory called C:php, where it will place all the files and subdirectories under that new directory. Next, go to the C:php directory and copy the php.ini- development file to php.ini. Now, to get a basic version of PHP working with Apache, you need to make a few minor modifications to the Apache configuration file. # gunzip < php-VERSION.tar.gz | tar xvf – AddType application/x-httpd-php .php s4s
  • 12. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 10 Integrating PHP with Apache on Windows To ensure that PHP and Apache get along with one another, you need to add a few items to the httpd.conf configuration file. First, find a section that looks like this: At the end of this section, add the following: In addition, add the following to ensure Apache knows where php.ini resides: Add the following line: This statement ensures that the PHP engine will parse files that end with the .php extension. Your selection of filenames might differ; for example, you might want to parse all *.html files as PHP files. Save the httpd.conf file and then restart Apache. The server should start without warning; PHP is now part of the Apache web server. Q) Explain Php.ini Basics Ans: php.ini Basics: After you have compiled or installed PHP, you can still change its behavior with the php.ini file. On Linux/UNIX systems, the default location for this file is /usr/local/php/lib or the lib subdirectory of the PHP installation location you used at configuration time. On a Windows system, this file should be in the PHP directory or another directory as specified by the value of PHPIniDir in the Apache httpd.conf file. Directives in the php.ini file come in two forms: values and flags. Value directives take the form of a directive name and a value separated by an equal sign. Possible values vary from directive to directive. Flag directives take the form of a directive name and a positive or negative term separated by an equal sign. Positive terms include 1, On, Yes, and True. Negative terms include 0, Off, No, and False. Whitespace is ignored. # Example: # LoadModule foo_module modules/mod_foo.so # LoadModule access_module modules/mod_access.so ... #LoadModule vhost_alias_module modules/mod_vhost_alias.so LoadModule php5_module C:/php/php5apache2_2.dll PHPIniDir "C:/php/" Next, look for this section: # # AddType allows you to add to or override the MIME configuration # file mime.types for specific file types. # AddType application/x-httpd-php .php s4s
  • 13. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 11 Q) Explain Basics of PHP Scripts Ans: When writing PHP, we need to inform the PHP engine that you want it to execute our commands. If we don't do this, the code you write will be mistaken for HTML and will be output to the browser. We can designate your code as PHP with special tags that mark the beginning and end of PHP code blocks. Table 4.1 shows four such PHP delimiter tags. Combining HTML and PHP You can incorporate this into an HTML document by simply adding HTML outside the PHP start and end tags, as shown in Listing 4.2. Q) Explain Basics Building Blocks of PHP (or) Explain Datatypes in PHP Ans: Variable: A variable is a special container that we can define, which then "holds" a value, such as a number, string, object, array, or a Boolean. PHP Variables A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). 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) s4s
  • 14. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 12 Example: Output: Datatypes in PHP:  Different types of data take up different amounts of memory and may be treated differently when they are manipulated by a script.  PHP is loosely typed, meaning that it automatically determines the data type at the time data is assigned to each variable.  Variables can be used flexibly-in one instance, a variable can hold a string and then later in the script it can hold an integer or some other data type. PHP supports the following data types: <?php $txt = SSGS Degree College"; echo " Welcome to $txt!"; ?> <?php $x = 5; $y = 4; echo $x + $y; ?> s4s
  • 15. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 13 Changing Type with settype():- settype() is used to change the type of a variable. Syntax:- settype($variabletochange, 'new type'); <?php $var1='98'; $var2='01'; settype($var1, "integer"); settype($var2, "integer"); echo ($var1.'<br>'); echo ($var2.'<br>'); echo ($var1+$var2.'<br>'); ?> Q) Explain Operators and Expressions in PHP Ans: An operator is a symbol or series of symbols that, when used in conjunction with values, performs an action, and usually produces a new value. PHP divides the operators in the following groups:  Arithmetic operators  Assignment operators  Comparison operators  Increment/Decrement operators  Logical operators  String operators  Array operators s4s
  • 16. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 14 Arithmetic operators The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc. Assignment operators The PHP assignment operators are used with numeric values to write a value to a variable. $x = 4; $x = $x + 4; // $x now equals 8 Comparison operators Comparison operators perform comparative tests using their operands and return the Boolean value true if the test is successful or false if the test fails. s4s
  • 17. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 15 Increment/Decrement operators These operators allow us to add or subtract the integer constant 1 from an integer variable, assigning the result to the variable itself. String operators PHP has two operators that are specially designed for strings. s4s
  • 18. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 16 Array operators: Q) Explain about Constants in PHP Ans: A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script. Create a PHP Constant To create a constant, use the define() function. Syntax define(name, value, case-insensitive) Parameters: 1. name: Specifies the name of the constant 2. value: Specifies the value of the constant 3. case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false The example below creates a constant with a case-sensitive name: Example <?php define("GREETING", "Welcome to W3Schools.com!"); echo GREETING; ?> s4s
  • 19. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 17 Q)Explain about the Switching Flow? Or Explain about the decision making and branching statements? Ans: It is common for scripts to evaluate conditions and change their behavior accordingly. These decisions are what make your PHP pages dynamic-that is, able to change output according to circumstances. PHP includes the following switching flow controls. 1. The if Statement 2. Using the else Clause with the if Statement 3. Using the elseif Clause with the if Statement 4. The switch Statement 5. Using the ?: Operator 1. The if Statement :- Syntax Example: 2. Using the else Clause with the if Statement: - Syntax Example: if (expression) { // code to execute if the expression evaluates to true } <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } ?> if (expression) { // code to execute if the expression evaluates to true } else { // code to execute in all other cases } <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> s4s
  • 20. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 18 3. Using the elseif Clause with the if Statement:- Syntax Example:- 4. The switch Statement :- Syntax:- if (expression) { // code to execute if the expression evaluates to true } elseif (another expression) { // code to execute if the previous expression failed // and this one evaluates to true } else { // code to execute in all other cases } <?php $t = time("H"); if ($t < "10") { echo "Have a good morning!"; } elseif ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } > switch (expression) { case result1: // execute this if expression results in result1 break; case result2: // execute this if expression results in result2 break; default: // execute this if no break statement // has been encountered hitherto } s4s
  • 21. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 19 Example:- 5. Using the ?: Operator The ?: or ternary operator is similar to the if statement, except that it returns a value derived from one of two expressions separated by a colon. Syntax:- If the test expression evaluates to true, the result of the second expression is returned; otherwise, the value of the third expression is returned. Example:- Q)Explain about the Loops? Or Iterative statements ? Ans: Loop statements are specifically designed to enable you to perform repetitive tasks because they continue to operate until a specified condition is achieved or until we explicitly choose to exit the loop. 1. The while Statement :- Syntax :- Example:- <?php $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!"; } ?> (expression) ? returned_if_expression_is_true : returned_if_expression_is_false; <?php $mood = "sad"; $text = ($mood == "happy") ? "I am in a good mood!" : "I am in a $mood mood."; echo "$text"; ?> while (expression) { // do something } <?php $x = 1; while ($x <= 5) { echo "The number is: $x <br>"; $x++; } ?> s4s
  • 22. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 20 2. The do...while Statement : Syntax:- Example:- 3. The for Statement Syntax:- Example:- Q)Explain about the Code Blocks and Browser Output? Ans:- 1. Open a notepad and type the following blocks code. (Start Allprogram notepad) 2. save it as a .php extension under xampp htdocs folder Code Block do { // code to be executed } while (expression); <?php $x = 1; do { echo "The number is: $x <br>"; $x++; } while ($x <= 5); ?> for (initialization expression; test expression; modification expression) { // code to be executed } <?php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } ?> s4s
  • 23. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 21 Run the php program by typing at the address bar of the firefox / chrome browser localhost/ex2.php the output will be displayed at the browser's document window Q) What is Function? Explain types of Functions in PHP Ans: A function is a self-contained block of code that can be called by your scripts. When called, the function's code is executed and performs a particular task. Types of Functions: Functions come in two types: those built in to the language and those you define Yourself (User Defined Functions). PHP has hundreds of built-in functions. Q) How to Declare User Defined Functions in PHP Ans: Defining a Function: You can define your own functions using the function statement: <html> <head> <title>Listing 5.14</title> </head> <body> <?php $display_prices = true; if ( $display_prices ) { ?> <table border="1"> <tr><td colspan="3">today's prices in dollars</td></tr> <tr><td>14</td><td>32</td><td>71</td> </table> <?php } ?> </body> </html> function some_function($argument1, $argument2) { //function code here Return; } s4s
  • 24. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 22 The name of the function follows the function statement and precedes a set of parentheses. A function can return a value using the return statement in conjunction with a value. The return statement stops the execution of the function and sends the value back to the calling code. Q) Explain Scope of Variables in Functions. Ans: A variable declared within a function remains local to that function. In other words, it is not available outside the function or within other functions. In larger projects, this can save you from accidentally overwriting the contents of a variable when you declare two variables with the same name in separate functions. Two types of Scope of Variables: 1. Local Variables 2. Global Variables 1. Local variables:- A Variable Declared Within a Function Is Unavailable Outside the Function The value of the variable $testvariable is not printed because no such variable exists outside the test() function. s4s
  • 25. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 23 2. Global Variables: A variable declare out side function can be used in function by using global statement. Ex: You can declare more than one variable at a time with the global statement by simply separating each of the variables you want to access with commas: global $var1, $var2, $var3; Q) Explain Static Statement in PHP Ans: Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example: Ex: <?php $num_of_calls = 0; function numberedHeading($txt) { global $num_of_calls; $num_of_calls++; echo "<h1>".$num_of_calls." ".$txt."</h1>"; } numberedHeading("SSGS Degree College"); echo "<p>Located in Guntakal.</p>"; numberedHeading("courses Offeres"); echo "<p>ALL Degree Gropus</p>"; ?> s4s
  • 26. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 24 Q) Explain More Function Arguments Ans: Setting Default Values for Arguments: PHP provides a nifty feature to help build flexible functions. Passing Variable References to Functions: When you pass arguments to functions, they are stored as copies in parameter variables. Any changes made to these variables in the body of the function are local to that function and are not reflected beyond it s4s
  • 27. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 25 Q) How to Create Arrays in PHP Ans: Arrays are indexed, which means that each entry is made up of a key and a value. The key is the index position, beginning with 0 and increasing incrementally by 1 with each new element in the array Creating Arrays You can create an array using either the array() function or the array operator []. The array() function is usually used when you want to create a new array The following code snippet shows how to create an array called $rainbow using the array() function, containing all its various colors: $rainbow = array("red", "orange", "yellow", "green", "blue", "indigo", "violet"); The following snippet shows the same array being created incrementally using the array operator: $rainbow[] = "red"; $rainbow[] = "orange"; $rainbow[] = "yellow"; $rainbow[] = "green"; $rainbow[] = "blue"; $rainbow[] = "indigo"; $rainbow[] = "violet"; Both snippets create a seven-element array called $rainbow, with values starting at index position 0 and ending at index position 6. Creating Associative Arrays: Whereas numerically indexed arrays use an index position as the key-0, 1, 2, and so forth-associative arrays use actual named keys. The following example demonstrates this by creating an array called $character with four elements: Creating Multi dimensional Arrays: The first two types of arrays hold strings and integers, whereas this third type holds other arrays. If each set of key/value pairs constitutes a dimension, a multidimensional array holds more than one series of these key/value pairs $character = array( "name" => "Bob", "occupation" => "superhero", "age" => 30, "special power" => "x-ray vision" ); s4s
  • 28. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 26 Q) Explain Some Array Related Functions in PHP Ans: Some Array-Related Constructs and Functions: More than 70 array-related functions are built in to PHP, which you can read about in detail at http://www.php.net/array. Some of the more common (and useful) functions are described briefly in this section: <?php $characters = array( array( "name" => "Bob", "occupation" => "superhero", "age" => 30, "special power" => "x-ray vision"), array( "name" => "Sally", "occupation" => "superhero", "age" => 24, "special power" => "superhuman strength"), array( "name" => "Jane", "occupation" => "arch villain", "age" => 45, "special power" => "nanotechnology")); ?> s4s
  • 29. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 27 . count() and sizeof()-Each of these functions counts the number of elements in an array; they are aliases of each other. Given the following array $colors = array("blue", "black", "red", "green"); both count($colors); and sizeof($colors); return a value of 4. . each() and list()-These functions (well, list() is a language construct that looks like a function) usually appear together, in the context of stepping through an array and returning its keys and values. You saw an example of this previously, where we stepped through the $c array and printed its contents. . foreach()-This control structure (that looks like a function) is used to step through an array, assigning the value of an element to a given variable, as you saw in the previous section. Q) How to Create and Work with Objects Ans: Creating an object is simple; you just declare it to be in existence: Now that you have a class, you can create a new instance of an object: output:- class myClass { //code will go here } $object1 = new myClass(); <?php class myClass { //code will go here } $object1 = new myClass(); echo "$object1 is an ".gettype($object1).".<br/>"; if (is_object($object1)) { echo "Really! I swear $object1 is an object!"; } ?> $object1 is an object. Really! I swear $object1 is an object! s4s
  • 30. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 28 Accessing Class Properties Within a Method: We can access class variables with in functions Constructors: A constructor is a function that lives within a class and, given the same name as the class, is automatically called when a new instance of the class is created using new classname. Using constructors enables you to provide arguments to your class which will then be processed immediately when the class is called Q) Explain Object Inheritance Ans: One class inherits functionality from its parent class A Class Inheriting from Its Parent If you save this code as inheritance.php, place it in your document root, and access it with your web browser, you will see the following on your screen: HELLO! My name is PHP <?php class myClass { public$name = "Sulthan"; function sayHello() { echo "HELLO! My name is ".$this->name; } } $object1 = new myClass(); $object1 -> sayHello(); ?> <?php class myClass { public$name = "Java"; function myClass($n) { $this->name = $n; } function sayHello() { echo "HELLO! My name is ".$this->name; } } class childClass extends myClass { //code goes here } $object1 = new childClass("PHP"); $object1 -> sayHello(); ?> s4s
  • 31. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 29 Q) How to work with Strings in PHP (or) Explain Conversion Specifiers in PHP Ans: PHP provides the following conversion specifications 1. Padding Output with a Padding Specifier The padding specifier should directly follow the percent sign that begins a conversion specification 2. Specifying a Field Width You can specify the number of spaces within which your output should sit. A field width specifier is an integer that should be placed after the percent sign that begins a conversion specification 3. Specifying Precision This proves particularly useful when dealing with currency. The precision identifier should be placed directly before the type specifier. It consists of a dot followed by the number of decimal places to which you want to round. This specifier has an effect only on data that is output with the f type specifier: <?php printf("%04d", 36); // prints "0036" ?> <?php printf("% 4d", 36) // prints " 36" ?> <?php echo "<pre>"; printf("%20sn", "Books"); printf("%20sn", "CDs"); printf("%20sn", "DVDs"); printf("%20sn", "Games"); printf("%20sn", "Magazines"); echo "</pre>"; ?> s4s
  • 32. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 30 <?php printf("%.2f", 5.333333); // prints "5.33" ?> 4. Type Specifier The printf() function requires a string argument, known as a format control string. It also accepts additional arguments of different types, which you learn about in a moment. The format control string contains instructions regarding the display of these additional arguments Q) Explain String Handling Functions in PHP Ans: a string as an array of characters, and thus you can access the individual characters of a string as if they were elements of an array: 1. strlen(): strlen() might be used to check the length of string <?php $test = "phpcoder"; echo $test[0]; // prints "p" echo $test[4]; // prints "o" ?> s4s
  • 33. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 31 2. strstr(): the strstr() function to test whether a string exists within another string. This function requires two arguments: the source string and the substring you want to find within it. 3. strpos(): The strpos() function requires two arguments: the source string and the substring you are seeking. The function also accepts an optional third argument, an integer representing the index from which you want to start searching. If the substring does not exist, strpos() returns false; otherwise, it returns the index at which the substring begins 4. substr(): substr() returns only that number of characters, from the start index onward: <?php $membership = "pAB7"; if (strlen($membership) == 4) { echo "<p>Thank you!</p>"; } else { echo "<p>Your membership number must be four characters long.</p>"; } ?> <?php $membership = "pAB7"; if (strstr($membership, "AB")) { echo "<p>Your membership expires soon!</p>"; } else { echo "<p>Thank you!</p>"; } ?> <?php $membership = "mz00xyz"; if (strpos($membership, "mz") === 0) { echo "Hello mz!"; } ?> <?php $test = "phpcoder"; echo substr($test,3)."<br/>"; // prints "coder" echo substr($test,3,2)."<br/>"; // prints "co" ?> s4s
  • 34. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 32 5. Strtok(): The function returns the next found token every time it is called, returning false when the end of the string is reached Q) How to Manipulate String in PHP (or) Explain trim(),ltrim() functions Ans: 1.trim(): The trim() function shaves any whitespace characters, including newlines, tabs, and spaces, from both the start and end of a string. 2. ltrim():The ltrim() function to strip whitespace from only the beginning of a string. this function with the string you want to transform and it returns a new string, shorn of tabs, newlines, and spaces <?php $test = "http://www.google.com/search?"; $test .= "hl=en&ie=UTF- 8&q=php+development+books&btnG=Google+Search"; $delims = "?&"; $word = strtok($test, $delims); while (is_string($word)) { if ($word) { echo $word."<br/>"; } $word = strtok($delims); } ?> <?php $text = "ttlots of room to breathe "; echo "<pre>$text</pre>"; // prints " lots of room to breathe "; $text = trim($text); echo "<pre>$text</pre>"; // prints "lots of room to breathe"; ?> s4s
  • 35. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 33 Q)Explain Date and Time Functions in PHP Ans: The PHP Date() Function: The PHP date() function convert a timestamp to a more readable date and time. The syntax of the PHP date() function can be given with. date(format, timestamp) Example 14/02/2018 Formatting the Dates and Times with PHP: The format parameter of the date() function is in fact a string that can contain multiple characters allowing you to generate a date string containing various components of the date and time, like day of the week, AM or PM, etc. Here are some the date-related formatting characters that are commonly used in format string: d - Represent day of the month; two digits with leading zeros (01 or 31) D - Represent day of the week in text as an abbreviation (Mon to Sun) m - Represent month in numbers with leading zeros (01 or 12) M - Represent month in text, abbreviated (Jan to Dec) y - Represent year in two digits (08 or 18) Y - Represent year in four digits (2008 or 2018) The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.), slashes (/), or spaces to add additional visual formatting. <?php $text = "ttlots of room to breathe "; echo "<pre>$text</pre>"; // prints " lots of room to breathe "; $text = ltrim($text); echo "<pre>$text</pre>"; // prints "lots of room to breathe "; ?> <?php $today = date("d/m/Y"); echo $today; ?> s4s
  • 36. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 34 Example Similarly you can use the following characters to format the time string: h - Represent hour in 12-hour format with leading zeros (01 to 12) H - Represent hour in in 24-hour format with leading zeros (00 to 23) i - Represent minutes with leading zeros (00 to 59) s - Represent seconds with leading zeros (00 to 59) a - Represent lowercase ante meridiem and post meridiem (am or pm) A - Represent uppercase Ante meridiem and Post meridiem (AM or PM) The PHP code in the following example displays the date in different formats: Example The PHP time() Function The time() function is used to get the current time as a Unix timestamp (the number of seconds since the beginning of the Unix epoch: January 1 1970 00:00:00 GMT). Example The above example produce the output as  1394003958 <?php echo date("d/m/Y") . "<br>"; echo date("d-m-Y") . "<br>"; echo date("d.m.Y"); ?> Output:- 14/02/2018 14/02/2018 14/02/2018 <?php echo date("h:i:s") . "<br>"; echo date("F d, Y h:i:s A") . "<br>"; echo date("h:i a"); ?> Output:- 04:34:58 February 14, 2018 04:34:58 AM 04:34 am <?php // Executed at March 05, 2014 07:19:18 $timestamp = time(); echo($timestamp); ?> s4s
  • 37. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 35 We can convert this timestamp to a human readable date through passing it to the previously introduce date() function. The above example produce the output as  March 05, 2014 07:19:18 The PHP mktime() Function: The mktime() function is used to create the timestamp based on a specific date and time. If no date and time is provided, the timestamp for the current date and time is returned. The syntax of the mktime() function can be given with: mktime(hour, minute, second, month, day, year) The following example displays the timestamp corresponding to 3:20:12 pm on May 10, 2014: Example The above example produce the output as  1399735212 The mktime() function can be used to find the weekday name corresponding to a particular date. To do this, simply use the 'l' (lowercase 'L') character with your timestamp, as in the following example, which displays the day that falls on April 1, 2014: Example <?php // Get the weekday name of a particular date echo date('l', mktime(0,0,0,1,4,2014)); ?> The above example produce the output as  Saturday The mktime() function can also be used to find a particular date in future after a specific time period. As in the following example, which displays the date which falls on after 30 month from the current date? <?php $timestamp = 1394003958; echo(date("F d, Y h:i:s", $timestamp)); ?> <?php // Create the timestamp for a particular date echo mktime(15, 20, 12, 5, 10, 2014); ?> s4s
  • 38. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 36 Example The above example produce the output as  05/09/2016 Q) How to Create Forms in PHP Ans: HTML forms are the principal means by which substantial amounts of information pass from the user to the server. Creating Forms:- In HTML, we can create forms by using the <form> </form> tag . This tag contains many internal tabs for creating form elements. <!DOCTYPE html> <html> <head> <title>A simple HTML form</title> 5: </head> <body> <form method="post" action="simpleform.php"> <p><label for="user">Name:</label><br/> <input type="text" id="user" name="user"></p> <p><label for="message">Message:</label><br/> <textarea id="message" name="message" rows="5" cols="40"></textarea></p> <button type="submit" name="submit" value="send">Send Message</button> </form> </body> </html> The FORM element's ACTION argument points to a file called simpleform.php, which processes the form information. The method of this form is POST, so the variables are stored in the $_POST superglobal Reading Input from a Form <!DOCTYPE html> <html> <head> <title>A simple response</title> </head> <body> <p>Welcome, <strong><?php echo $_POST['user']; ?></strong>!</p> <?php // Executed at March 05, 2014 $futureDate = mktime(0,0,0,date("m")+30,date("d"),d ate("Y")); echo date("d/m/Y", $futureDate); ?> s4s
  • 39. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 37 <p>Your message is: <strong><?php echo $_POST['message']; ?></strong></p> </body> </html> Q) How to Access Form Input with User Defined Arrays Ans: We can read the multiple inputs by defining form check box as an array which is defined with in the <input> tag. Example:- <input type="checkbox" id="tricorder" name="products[]" value="Tricorder"> An HTML Form Including Multiple Check Boxes <!DOCTYPE html> <html> <head> <title>An HTML form with checkboxes</title> </head> <body> <form action="send_formwithcb.php" method="POST"> <p><label>Name:</label><br/> <input type="text" name="user" /></p> <fieldset> <legend>Select Some Products:</legend><br/> <input type="checkbox" id="1101" name="products[]" value="Grinder"> <label for="grinder">Grinder</label><br/> <input type="checkbox" id="1102" name="products[]" value="Tablemate"> <label for="tablemate">Tablemate</label><br/> <input type="checkbox" id="1103" name="products[]" value="Printer"> <label for="printer">HAL 2000</label> </fieldset> <button type="submit" name="submit" value="submit">Submit Form</button> </form> </body> </html> s4s
  • 40. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 38 Accessing Form elements using array in PHP: The following php program illustrates how to access multiple array values. <!DOCTYPE html> <html> <head> <title>Reading checkboxes</title> </head> <body> <p>Welcome, <strong><?php echo $_POST['user']; ?></strong>!</p> <p>Your product choices are: <?php if (!empty($_POST['products'])) { echo "<ul>"; foreach ($_POST['products'] as $value) { echo "<li>$value</li>"; } echo "</ul>"; } else { echo "None"; } ?> </body> </html> Now access the form (formwithcb.html) with your web browser and check some checkboxes. Figure shows an example s4s
  • 41. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 39 Q) Explain about Hidden Fields to Save State Ans: A hidden field behaves the same as a text field, except that the user cannot see it unless he views the HTML source of the document that contains it. Take the original numguess.php script and save a copy as numguess2.php. In the new version, add a line after the initial assignment of the $num_to_guess variable: $num_tries = (isset($_POST['num_tries'])) ? $num_tries + 1 : 1; This line initializes a variable called $num_tries and assigns a value to it. If the form has not yet been submitted (if $_POST['num_tries'] is empty), the value of the $num_tries variable is 1 because you are on your first attempt at guessing the number. If the form has already been sent, the new value is the value of $_POST['num_tries'] plus 1. Saving State with a Hidden Field <?php $num_to_guess = 42; $num_tries = (isset($_POST['num_tries'])) ? $num_tries + 1 : 1; if (!isset($_POST['guess'])) { $message = "Welcome to the guessing machine!"; } elseif (!is_numeric($_POST['guess'])) { // is not numeric $message = "I don't understand that response."; } elseif ($_POST['guess'] == $num_to_guess) { // matches! $message = "Well done!"; } elseif ($_POST['guess'] > $num_to_guess) { $message = $_POST['guess']." is too big! Try a smaller number."; } elseif ($_POST['guess'] < $num_to_guess) { $message = $_POST['guess']." is too small! Try a larger number."; } else { // some other condition $message = "I am terribly confused."; } ?> <!DOCTYPE html> <html> <head> <title>A PHP number guessing script</title> </head> <body> <h1><?php echo $message; ?></h1> <p><strong>Guess number:</strong> <?php echo $num_tries; ?></p> s4s
  • 42. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 40 <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"> <p><label for="guess">Type your guess here:</label><br/> <input type="text" id="guess" name="guess" /></p> <input type="hidden" name="num_tries" value="<?php echo $num_tries; ?>"/> <button type="submit" name="submit" value="submit">Submit</button> </form> </body> </html>  The counter should increment by 1 each time you access the form. Q) Explain Redirecting User Ans: When a server script communicates with a client, it must first send some headers that provide information about the document to follow. PHP usually handles this for you automatically, but you can choose to send your own header lines with PHP's header() function <html> <head> <title> Redirecting Page with Header</title> </head> <body> <h1> Press the Submit to Redirect </h1> <br> <form action="redirectme.php" method="POST"> <input type="submit" name="submitbutton" value="Submit"/> </form> </body> </html> redirectme.php: <?php $submitbutton= $_POST['submitbutton']; if ($submitbutton) { header("Location: http://www.skuniversity.ac.in/"); } ?> s4s
  • 43. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 41 Q) Explain Sending Mail on Form Submission Ans: The mail() function of PHP to send information like, suggestions/messages to specific email address on form submission. The mail() function with four parameters to send email as follows: mail("$to", $subject, $message, $headers);  $to variable is to store receiver's email id.  $subject is a variable to store mail subject.  $message is a variable to store user's message.  $headers contains other email parameters like BCc, Cc etc. Q) How to Upload a File in PHP Ans: There is one global PHP variable called $_FILES. This variable is an associate double dimension array and keeps all the information related to uploaded file. So if the value assigned to the input's name attribute in uploading form was file, then PHP would create following five variables – $_FILES['file']['tmp_name'] - the uploaded file in the temporary directory on the web server. s4s
  • 44. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 42 $_FILES['file']['name'] - the actual name of the uploaded file. $_FILES['file']['size'] - the size in bytes of the uploaded file. $_FILES['file']['type'] - the MIME type of the uploaded file. $_FILES['file']['error'] - the error code associated with this file upload. Example:- <html> <head> <title>File Upload</title> </head> <body> <form action="uploader.php" method="post" enctype="multipart/form-data"> Select File: <input type="file" name="fileToUpload"/> <input type="submit" value="Upload Image" name="submit"/> </body> </form> uploader.php <?php $target_path = "e:/"; $target_path = $target_path.basename( $_FILES['fileToUpload']['name']); if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) { echo "File uploaded successfully!"; } else{ echo "Sorry, file not uploaded, please try again!"; } ?> Q) Explain about Cookies and How to Set Cookies A cookie is a small amount of data stored by the user's browser in compliance with a request from a server or script. A single host can request that up to 20 cookies be stored by a user's browser. Each cookie consists of a name, value, and expiration date, as well as host and path information. The size of an individual cookie is limited to 4KB. s4s
  • 45. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 43 PHP Create/Retrieve a Cookie / modify the cookie setcookie() - used to create cookie and modify the cookie, the global variable $_COOKIE used to retrieve the cookie. 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> 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> Q) What is Session? Explain, how to Start(set) and Destroy(unset) Sessions (or) Explain about the sessions? (or) Explain about the Session Function Overview, Starting a Session, Working with session variables, Destroying Sessions and Unsetting Variables? Ans: A session is a way to store information (in variables) to be used across multiple page (e.g. username, favorite color, etc). Session Function Overview: Session functions provide a unique identifier to a user, which can then be used to store and acquire information linked to that ID. When a visitor accesses a session enabled page, either a new identifier is allocated or the user is re-associated with one that was already established in a previous visit. Any variables that have been associated with the session become available to your code through the $_SESSION superglobal. s4s
  • 46. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 44 $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; Starting a Session :- we must find the following line in your php.ini file and change the value from 0 to 1 (and restart the web server): session.auto_start = 0 A session is started with the session_start() function. The session_id() function enables you to either set or retrieve a session ID. Example :- <?php // Start the session session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Set session variables $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; echo "Session variables are set."; ?> </body> </html> printing session_id() :- session_id() used to set or retrieve a session ID. Example program :- <?php session_start(); echo "<p>Your session ID is ".session_id().".</p>"; ?> Working with Session Variables :- When a session is started, we can store any number of variables in the $_SESSION superglobal and then access them on any session-enabled page. The following program shows that the accessing session variables. <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Echo session variables that were set on previous page echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>"; echo "Favorite animal is " . $_SESSION["favanimal"] . "."; ?> </body> </html> s4s
  • 47. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 45 Destroying Sessions and Unsetting Variables To remove all global session variables and destroy the session, use session_unset() and session_destroy(): Example :- <?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // remove all session variables session_unset(); // destroy the session session_destroy(); ?> </body> </html> Q) Explain about Include and require Ans: There are two PHP functions which can be used to included one PHP file into another PHP file. 1. The include() Function 2. The require() Function Theinclude() Function The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution. <html> <body> <?php include("menu.php"); ?> <p>This is an example to show how to include PHP file!</p> </body> </html> The require() Function The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script. s4s
  • 48. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 46 <html> <body> <?php require("menu.php"); ?> <p>This is an example to show how to include PHP file!</p> </body> </html> Q) How to Validate Files Ans: PHP provides many functions to help you to discover information about files on your system. The file_exists() function. This function requires a string representation of an absolute or relative path to a file, which might or might not be present. If the file is found, the file_exists() function returns true; otherwise, it returns false: if (file_exists('test.txt')) { echo "The file exists!"; } The is_file() function requires the file path and returns a Boolean value: if (is_file('test.txt')) { echo "test.txt is a file!"; } The is_readable() function accepts the file path as a string and returns a Boolean value: if (is_readable('test.txt')) { echo "test.txt is readable"; } The is_writable() function tells you whether you have the proper permission to write to a file. As with is_readable(), the is_writable() function requires the file path and returns a Boolean value. if (is_writable('test.txt')) { echo "test.txt is writable"; } The filesize() function attempts to determine and return its size in bytes. It returns false if it encounters problems: echo "The size of test.txt is ".filesize('test.txt'); Q) Explain Creating and Deleting Files PHP Create File - fopen() 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:- $myfile = fopen("testfile.txt", "w") The most common modes are read (r), write (w), and append (a). s4s
  • 49. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 47 The fopen() function returns a file resource you use later to work with the open file. To open a file for reading, you use the following: $fp = fopen("test.txt", "r"); You use the following to open a file for writing: $fp = fopen("test.txt", "w"); To open a file for appending (that is, to add data to the end of a file), you use this: $fp = fopen("test.txt", "a"); Reading from Files The fread() function accepts a file resource as an argument, as well as the number of bytes you want to read. The fread() function returns the amount of data you requested, unless the end of the file is reached first: $chunk = fread($fp, 16); Reading a File with fread() <?php $filename = "test.txt"; $fp = fopen($filename, "r") or die("Couldn't open $filename"); 4: while (!feof($fp)) { $chunk = fread($fp, 8); echo $chunk."<br/>"; } ?> Q) How to Create Directories in PHP Ans: The mkdir() function enables you to create a directory. The mkdir() function requires a string that represents the path to the directory you want to create and an octal number integer that represents the mode you want to set for the directory. Remember, you specify an octal (base 8) number using a leading 0; for example, 0777 or 0400. s4s
  • 50. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 48 The rmdir() function enables you to remove a directory from the filesystem if the process running your script has the right to do so, and if the directory is empty. The rmdir() function requires only a string representing the path to the directory you want to delete. rmdir("testdir"); The opendir() function returns a directory handle unless the directory isn't present or readable; in that case, it returns false: $dh = opendir("testdir"); The readdir() returns only the names of its items, rather than full paths Ex: <?php $dirname = "."; $dh = opendir($dirname) or die("Couldn't open directory"); while (!(($file = readdir($dh)) === false ) ) { if (is_dir("$dirname/$file")) { echo "(D) "; } echo $file."<br/>"; } closedir($dh); ?> Q) Explain about Creating of Images using PHP Ans: Drawing a New Image The basic PHP function used to create a new image is called ImageCreate(),The following line creates a drawing area that is 300 pixels wide by 300 pixels high: s4s
  • 51. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 49 $myImage = ImageCreate(300,300); The following examples define five such colors (black, white, red, green, and blue, respectively), using the ImageColorAllocate() function and RGB values: $black = ImageColorAllocate($myImage, 0, 0, 0); $white = ImageColorAllocate($myImage, 255, 255, 255); $red = ImageColorAllocate($myImage, 255, 0, 0); $green = ImageColorAllocate($myImage, 0, 255, 0); $blue = ImageColorAllocate($myImage, 0, 0, 255); Drawing Shapes and Lines Several PHP functions can assist you in drawing shapes and lines on your canvas: . ImageEllipse() is used to draw an ellipse. . ImageArc() is used to draw a partial ellipse. . ImagePolygon() is used to draw a polygon. . ImageRectangle() is used to draw a rectangle. . ImageLine() is used to draw a line. Getting Fancy with Pie Charts Defining the canvas, defining the colors, and then drawing and filling. We can use this same sequence of events to expand your scripts to create charts and graphs, using either static or dynamic data for the data points. s4s
  • 52. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 50  //draw a pie  ImageFilledArc($myImage, 100, 100, 200, 150, 0, 90, $red, IMG_ARC_PIE);  ImageFilledArc($myImage, 100, 100, 200, 150, 90, 180 , $green, IMG_ARC_PIE);  ImageFilledArc($myImage, 100, 100, 200, 150, 180, 360 , $blue, IMG_ARC_PIE); Image Creation from User Input In addition to creating images from other images and drawing images on your own, you can create images based on user input. s4s
  • 53. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 51 Q) Explain Importance of Good Database Design Ans: A good database design is crucial for a high-performance application, thinking about relationships and database efficiency-which includes ease of maintenance, minimizing duplications, and avoiding inconsistencies-is part of normalization. So, before you even start coding an application, spend a lot of time designing your database. Q) Explain Types of Table Relationships Ans: Table relationships come in several forms: . One-to-one relationships . One-to-many relationships . Many-to-many relationships One-to-One Relationships In a one-to-one relationship, a key appears only once in a related table. for example, if each employee is assigned one computer within a company. Figure shows the one-to-one relationship of employees to computers s4s
  • 54. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 52 One-to-Many Relationships In a one-to-many relationship, keys from one table appear multiple times in a related table. The example shown in Figure indicating a connection between employees and departments, illustrates a one-to-many relationship Many-to-Many Relationships In a many-to-many relationship, the key value of one table can appear many times in a related table. So far, it sounds like a one-to-many relationship the example of students and classes: A student has an ID and a name. A class has an ID and a name. A student usually takes more than one class at a time, and a class always contains more than one student, as you can see in Figure. Q) Explain Normalization Ans: Normalization is the process of minimizing redundancy from a relation or set of relations. Redundancy in relation may cause insertion, deletion and updation anomalies. So, s4s
  • 55. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 53 it helps to minimize the redundancy in relations. Normal forms are used to eliminate or reduce redundancy in database tables. First normal form (1NF) As per the rule of first normal form, an attribute (column) of a table cannot hold multiple values. It should hold only atomic values. Second normal form (2NF) A table is said to be in 2NF if both the following conditions hold:  Table is in 1NF (First normal form)  No non-prime attribute is dependent on the proper subset of any candidate key of table.  An attribute that is not part of any candidate key is known as non-prime attribute. Third Normal form (3NF) A table design is said to be in 3NF if both the following conditions hold: Table must be in 2NF Transitive functional dependency of non-prime attribute on any super key should be removed. An attribute that is not part of any candidate key is known as non-prime attribute. In other words 3NF can be explained like this: A table is in 3NF if it is in 2NF and for each functional dependency X-> Y at least one of the following conditions hold: X is a super key of table Y is a prime attribute of table An attribute that is a part of one of the candidate keys is known as prime attribute. Q) Explain MySQL Datatypes Ans:- The type of fields (or columns) are also referred to as data types, after the type of data you will be storing in those fields. MySQL uses many different data types broken into three categories -  Numeric  Date and Time  String Types. Numeric Data Types The following list shows the common numeric data types and their descriptions INT - A normal-sized integer that can be signed or unsigned. You can specify a width of up to 11 digits. TINYINT - A very small integer that can be signed or unsigned. You can specify a width of up to 4 digits. SMALLINT - A small integer that can be signed or unsigned. You can specify a width of up to 5 digits. MEDIUMINT - A medium-sized integer that can be signed or unsigned. You can specify a width of up to 9 digits. BIGINT - A large integer that can be signed or unsigned. 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, s4s
  • 56. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 54 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 and Time Types The MySQL date and time datatypes 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. DATETIME - 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. TIMESTAMP - 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 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 -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. 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 - A BLOB or TEXT column with a maximum length of 4294967295 characters. You do not specify a length with LONGBLOB or LONGTEXT. s4s
  • 57. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 55 ENUM - An enumeration, which is a fancy term for list. Q) Explain Some MySQL Commands (or) Explain DML,DQL,DCL Commands Ans: Create Command:The generic table-creation syntax is CREATE TABLE table_name (column_name column_type); The table name is up to you, of course, but should be a name that reflects the usage of the table. CREATE TABLE grocery_inventory ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, item_name VARCHAR (50) NOT NULL, item_desc TEXT, item_price FLOAT NOT NULL, curr_qty INT NOT NULL ); Insert Command: The basic syntax of INSERT is INSERT INTO table_name (column list) VALUES (column values); Within the parenthetical list of values, you must enclose strings within quotation marks. The SQL standard is single quotes, but MySQL enables the usage of either single or double quotes. Select Command: SELECT is the SQL command used to retrieve records from your tables. This command syntax can be totally simple or very complicated, depending on which fields you want to select, whether you want to select from multiple tables, and what conditions you plan to impose The most basic SELECT syntax looks like this: SELECT expressions_and_columns FROM table_name [WHERE some_condition_is_true] [ORDER BY some_column [ASC | DESC]] [LIMIT offset, rows] Ordering SELECT Results If you want to order results a specific way, such as by date, ID, name, and so on, specify your requirements using the ORDER BY clause. In the following statement, the intention is a resultset ordered alphanumerically by item_name: SELECT id, item_name, curr_qty FROM grocery_inventory ORDER BY item_name; Success! The results are as follows: s4s
  • 58. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 56 The default sorting of ORDER BY results is ascending (ASC); strings sort from A to Z, integers start at 0, and dates sort from oldest to newest. You can also specify a descending sort, using DESC: Using WHERE in Your Queries This is when the WHERE clause comes in to play. From the example SELECT syntax, you see that WHERE is used to specify a particular condition: SELECT expressions_and_columns FROM table_name [WHERE some_condition_is_true] An example is to retrieve all the records for items with a quantity of 500: SELECT * FROM grocery_inventory WHERE curr_qty = 500; Here are the results: String Comparison Using LIKE To matching strings within a WHERE clause by using = or !=, but there's another useful operator for the WHERE clause when comparing strings: the LIKE operator. This operator uses two characters as wildcards in pattern matching:  % -Matches multiple characters  _ -Matches exactly one character SELECT * FROM grocery_inventory WHERE item_name LIKE 'A%'; Here are the results: Update Command: UPDATE is the SQL command used to modify the contents of one or more columns in an existing record or set of records. The most basic UPDATE syntax looks like this: UPDATE table_name SET column1='new value', column2='new value2' [WHERE some_condition_is_true] s4s
  • 59. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 57 Replace Command: Another method for modifying records is to use the REPLACE command, which is remarkably similar to the INSERT command. REPLACE INTO table_name (column list) VALUES (column values); The REPLACE statement works like this: If the record you are inserting into the table contains a primary key value that matches a record already in the table, the record in the table is deleted and the new record inserted in its place. REPLACE INTO grocery_inventory VALUES (1, 'Granny Smith Apples', 'Sweet!', '0.50', 1000); Delete Command: The basic DELETE syntax is as follows: DELETE FROM table_name [WHERE some_condition_is_true] [LIMIT rows] Q)Explain about Joins in MySQL Ans: MySQL JOINS are used to retrieve data from multiple tables. A MySQL JOIN is performed whenever two or more tables are joined in a SQL statement. There are different types of MySQL joins: 1. MySQL INNER JOIN (or sometimes called simple join) 2. MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN) 3. MySQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN) INNER JOIN (simple join) MySQL INNER JOINS return all rows from multiple tables where the join condition is met. The syntax for the INNER JOIN in MySQL is: Visual Illustration: In this visual diagram, the MySQL INNER JOIN returns the shaded area: SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column; s4s
  • 60. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 58 The MySQL INNER JOIN would return the records where table1 and table2 intersect. LEFT OUTER JOIN: This type of join returns all rows from the LEFT-hand table specified in the ON condition and only those rows from the other table where the joined fields are equal (join condition is met). The syntax for the LEFT OUTER JOIN in MySQL is: In some databases, the LEFT OUTER JOIN keywords are replaced with LEFT JOIN. Visual Illustration In this visual diagram, the MySQL LEFT OUTER JOIN returns the shaded area: The MySQL LEFT OUTER JOIN would return the all records from table1 and only those records from table2 that intersect with table1. RIGHT OUTER JOIN This type of join returns all rows from the RIGHT-hand table specified in the ON condition and only those rows from the other table where the joined fields are equal (join condition is met). Syntax The syntax for the RIGHT OUTER JOIN in MySQL is: In some databases, the RIGHT OUTER JOIN keywords are replaced with RIGHT JOIN. SELECT columns FROM table1 LEFT [OUTER] JOIN table2 ON table1.column = table2.column; SELECT columns FROM table1 RIGHT [OUTER] JOIN table2 ON table1.column = table2.column; s4s
  • 61. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 59 Visual Illustration In this visual diagram, the MySQL RIGHT OUTER JOIN returns the shaded area: The MySQL RIGHT OUTER JOIN would return the all records from table2 and only those records from table1 that intersect with table2. Q) Explain about Subqueries Ans: A subquery is a SELECT statement that appears within another SQL statement. Such queries can prove extremely useful because they often eliminate the need for JOIN queries, and in the case of application programming, subqueries can eliminate the need for multiple queries within loops An example of the basic subquery syntax is shown here: SELECT expressions_and_columns FROM table_name WHERE somecolumn = (SUBQUERY); You can also use subqueries with UPDATE and DELETE statements, as shown here: DELETE FROM table_name WHERE somecolumn = (SUBQUERY); or UPDATE table_name SET somecolumn = 'something' WHERE somecolumn = (SUBQUERY); The following example uses a subquery to obtain records from users in the master_ name table who have an email address in the email table: SELECT firstname, lastname FROM master_name WHERE name_id IN (SELECT name_id FROM email); The results of this query may look something like this: s4s
  • 62. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 60 Q) Explain Frequently Used String Functions in MySQL Ans: MySQL's built-in string-related functions can be used several ways. You can use functions in SELECT statements without specifying a table to retrieve a result of the function. count characters in a string. SELECT LENGTH('This is cool!'); The result is this: 13 SELECT CONCAT('My', 'S', 'QL'); This query results in the following: RTRIM() and LTRIM() functions remove whitespace from either the right or left side of a string: SELECT RTRIM('stringstring '); Stringstring The LOCATE() function returns the position of the first occurrence of a given substring within the target string. For example, you can look for a needle in a haystack: SELECT LOCATE('needle', 'haystackneedlehaystack'); You should see this result: 9 The MySQL LCASE() and UCASE() functions transform a string into lowercase or uppercase: SELECT LCASE('MYSQL'); Result: mysql Repeat() string-manipulation function is which does just what it sounds like SELECT REPEAT("bowwow", 4); You should see this result: bowwowbowwowbowwowbowwow | The REPLACE() function replaces all occurrences of a given string with another string: SELECT REPLACE('bowwowbowwowbowwowbowwow', 'wow', 'WOW'); Result: bowWOWbowWOWbowWOWbowWOW s4s
  • 63. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 61 Q) How to Use Data and Time Functions in MySQL Ans:- MySQL's built-in date-related functions in SELECT statements, with or without specifying a table, to retrieve a result of the function Working with Days The DAYOFWEEK() and WEEKDAY() functions do similar things with slightly different results. 2 and 0 for Monday The DAYOFMONTH() and DAYOFYEAR() functions are more straightforward, with only one result and a range that starts at 1 and ends at 31 for DAYOFMONTH() and 366 for DAYOFYEAR(). Working with Months and Years MONTH() and MONTHNAME() return the number of the month in a year and the name of the month for a given date. For example: SELECT MONTH('2012-01-09'), MONTHNAME('2012-01-09'); 1 January Working with Weeks: Working with Weeks there can be 53 weeks in a year if Sunday is the first day of the week and December hasn't ended. s4s
  • 64. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 62 Working with Hours, Minutes, and Seconds There are functions to find the hours, minutes, and seconds from that string.These functions are called HOUR(), MINUTE(), and SECOND(). HOUR() returns the hour in a given time, which is between 0 and 23. The range for MINUTE() and SECOND() is 0 to 59. 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; Q) What is Transaction? Ans: A transaction is a sequential group of database manipulation operations, which is performed as if it were one single work unit. In other words, a transaction will never be complete unless each individual operation within the group is successful. If any operation within the transaction fails, the entire transaction will fail. Output: s4s
  • 65. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 63 Properties of Transactions Transactions have the following four standard properties, usually referred to by the acronym ACID - Atomicity - This ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state. Consistency - This ensures that the database properly changes states upon a successfully committed transaction. Isolation - This enables transactions to operate independently on and transparent to each other. Durability - This ensures that the result or effect of a committed transaction persists in case of a system failure. COMMIT and ROLLBACK These two keywords Commit and Rollback are mainly used for MySQL Transactions. When a successful transaction is completed, the COMMIT command should be issued so that the changes to all involved tables will take effect. If a failure occurs, a ROLLBACK command should be issued to return every table referenced in the transaction to its previous state. Q) What are Stored Procedures Ans: a stored procedure is a procedure in SQL that is stored in the database server rather than the web server By using stored procedures in code point to performance and maintenance as key reasons for doing so: 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 // The name of the stored procedure is sp1: CREATE PROCEDURE sp1 () SELECT * FROM testSP WHERE date_added BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() // To call the stored procedure, use the CALL command: CALL sp1 () // s4s
  • 66. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 64 Q) Explain about mysql() Vs mysqli() Functions Ans: There are too many differences between these PHP database extensions. These differences are based on some factors like performance, library functions, features, benefits, and others. MySQL MySQLi MySQL extension added in PHP version 2.0. and deprecated as of PHP 5.5.0. Does not support prepared statements. MySQL provides the procedural Interface MySQL extension does not support stored procedure MySQL extension lags in security and other special features, comparatively. Transactions are handled by SQL queries only. Extension directory: ext/mysql. MySQLi extension added in PHP 5.5 and will work on MySQL 4.1.3 or above. MySQLi supports prepared statements. MySQLi provides both procedural and object-oriented interface. MySQLi supports store procedure. MySQLi extension is with enhanced security and improved debugging. MySQLi supports transactions through API. Extension directory: ext/mysqli. Q) How to Connect MySQL with PHP Ans: Making a Connection The basic syntax for a connection to MySQL is as follows: $mysqli = mysqli_connect("hostname", "username", "password", "database"); The value of $mysqli is the result of the function and is used in later functions for communicating with MySQL. With sample values inserted, the connection code looks like this: $mysqli = mysqli_connect("localhost", "joeuser", "somepass", "testDB"); A Simple Connection Script s4s
  • 67. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 65 Executing Queries: The mysqli_query() function in PHP is used to send your SQL query to MySQL. The mysqli_query function returns a value of true or false, and this value is checked in the if...else statement If the value of $res is true, a success message is printed to the screen. If you access MySQL through the command-line interface to verify the creation of the table <?php $dbhost = 'localhost:3306'; $dbuser = 'root'; $dbpass = 'root'; $dbname = 'test'; $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; $sql = "INSERT INTO Persons (PersonID,LastName,FirstName,Address,City) VALUES ('7', 'sdf', 'sdfad', 'knl', 'beng')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } mysqli_close($conn); ?> <?php $dbhost = 'localhost:3306'; $dbuser = 'root'; $dbpass = 'root'; $dbname = 'test'; $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysqli_close($conn); ?> s4s
  • 68. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 66 <?php $dbhost = 'localhost:3306'; $dbuser = 'root'; $dbpass = 'root'; $dbname = 'test'; $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); if(! $conn ) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; $sql = "select * from Persons"; $res=mysqli_query($conn,$sql); if($res){ $num_of_rows=mysqli_num_rows($res); printf("Result Set %d rows n",$num_of_rows); } else { printf("Could Not Retrive",mysqli_error($mysqli)); } mysqli_free_result($res); mysqli_close($conn); ?> Q) Create Online Address Book Ans: creating a manageable online address book. You learn how to create the relevant database tables, as well as the forms and scripts for adding, deleting, and viewing database records. These basic concepts are the foundations of developing any application that uses CRUD functionality (create, read, update, delete), which is precisely what a lot of web-based applications. s4s
  • 69. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 67 Planning and Creating the Database Tables In an online address book, a set of related tables helps alleviate the redundancy and repetition of information and allows you to display all information in a unified view. Creating a Menu s4s
  • 70. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 68 Creating the Record-Addition Mechanism s4s
  • 71. PHP, MySQL & WORDPRESS Prepared By D.SULTHAN BASHA M.Sc., Lecturer in Computer Science Page 69 Viewing Records Showing Records: s4s
  • 72. DEPARTMENT OF COMPUTER SCIENCE SSGS-DC-GTL B.Sc (Computer Science) – Cluster C1 Page 70 Q) What is WordPress? Explain its Features Ans: WordPress is an open source Content Management System (CMS), which allows the users to build dynamic websites and blogs. WordPress is the most popular blogging system on the web and allows updating, customizing and managing the website from its back-end CMS and components. Features:  User Management: It allows managing the user information such as changing the role of the users to (subscriber, contributor, author, editor or administrator), create or delete the user, change the password and user information. The main role of the user manager is Authentication.  Media Management: It is the tool for managing the media files and folder, in which you can easily upload, organize and manage the media files on your website.  Theme System: It allows modifying the site view and functionality. It includes images, stylesheet, template files and custom pages.  Extend with Plugins: Several plugins are available which provides custom functions and features according to the users need.  Search Engine Optimization: It provides several search engine optimization (SEO) tools which makes on-site SEO simple.  Multilingual: It allows translating the entire content into the language preferred by the user.  Importers: It allows importing data in the form of posts. It imports custom files, comments, post pages and tags. Q) Explain about WAMP and XAMP(bitnami) Servers. Ans: 1. WampServer is a Windows web development environment. It allows you to create web applications with Apache2, PHP and a MySQL database. Alongside, PhpMyAdmin allows you to manage easily your databases. Using wampserver  The "www" directory will be automatically created (usually c:wampwww)  Create a subdirectory in "www" and put your PHP files inside.  Click on the "localhost" link in the WampSever menu or open your internet browser and go to the URL : http://localhost s4s