VII Unit
VII Unit
7.PHP &MySQL
With PHP, you can connect to and manipulate databases.MySQL is the most popular database
system used with PHP.
What is MySQL?
MySQL is a database system used on the web
MySQL is a database system that runs on a server
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, and easy to use
MySQL supports standard SQL
MySQL compiles on a number of platforms
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle Corporation
The data in MySQL is stored in tables. A table is a collection of related data, and it consists of
columns and rows.
Databases are useful when storing information categorically. A company may have a database
with the following tables:
Employees
Products
Customers
Orders
PHP + MySQL
PHP combined with MySQL are cross-platform (you can develop in Windows and serve
on a Unix platform)
Queries
A query is a question or a request.
We can query a database for specific information and have a recordset returned.
The query above selects all the data in the "LastName" column from the "Employees" table.
`
The truth is that MySQL is the de-facto standard database system for web sites with HUGE
volumes of both data and end users (like Friendster, Yahoo, and Google).
Syntax
mysql_connect (host, username, password);
Parameter Description
Note: There are more available parameters, but the ones listed above are the most important.
In the following example we store the connection in a variable ($con) for later use in the script:
<?php
// Create connection
$con=mysql_connect ("$localhost”,”root”,””) or die(mysql_error());
?>
`
Mysql_error():function returns an system generate error message if any failure in the connection
ocuur.
Create database:
A database holds one or more tables. The create database statement is used to create a database
table in MySQL. We must add the create database statement to the mysql_query() function to
execute the command.
<?php
//create database
?>
Here webtech is the new database that was created.if any failure in the database occur then
mysql_error() function generate an error message.
Selecting database:
<?php
Mysql_select_db(“webtech”);
?>
<?php
//creating table
mysql_query("create table php(rno int,name varchar(30),age int)") or die(mysql_error());
echo "table inserted";
?>
Here php is the table name that created on the database webtech.
The insert command used to insert data into table of the selected database.
<?php
//insert record into table
mysql_query("insert into php values(100,'JOHN',29)") or die(mysql_error());
echo "one row inserted";
?>
Delete database:
Delete command is used to delete the entire database from mysql.
<?php
`
Close a Connection
The connection will be closed automatically when the script ends. To close the connection
before, use the mysql_close () function:
<? Php
$con=mysql_connect ("localhost","root","");
mysql_close($con);
?>
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
To get PHP to execute the statement above we must use the mysql_query () function. This
function is used to send a query or command to a MySQL connection.
********Special functions:******
mysql_num_rows:
retrieves the number of rows from a result set. this command is only valid for statements like
select or show that return an actual result set. to retrieve the number of rows affected by a insert,
update, replace or delete query, use mysql_affected_rows().
parameters:
result
the result resource that is being evaluated. this result comes from a call to mysql_query().
`
return values
examples
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>
mysql_real_escape_string():
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL] )
Escapes special characters in the unescaped_string, taking into account the current character set
of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted,
this function must be used.
This function must always (with few exceptions) be used to make data safe before sending a
query to MySQL.
mysql_set_charset():
Description
bool mysql_set_charset ( string $charset [, resource $link_identifier = NULL ] )
`
Parameters
charset
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened
by mysql_connect() is assumed. If no such link is found, it will try to create one as
if mysql_connect() was called with no arguments. If no connection is found or
established, an E_WARNING level error is generated.
Return Values
mysql_unbuffered_query:
mysql_unbuffered_query — Send an SQL query to MySQL without fetching and buffering the
result rows.
Description
resource mysql_unbuffered_query ( string $query [, resource $link_identifier =
NULL ] )
Parameters
query
link_identifier
The MySQL connection. If the link identifier is not specified, the last link opened
by mysql_connect() is assumed. If no such link is found, it will try to create one as
if mysql_connect() was called with no arguments. If no connection is found or
established, an E_WARNING level error is generated.
Return Values
Note:
The benefits of mysql_unbuffered_query() come at a cost: you cannot
use mysql_num_rows() andmysql_data_seek() on a result set returned
from mysql_unbuffered_query(), until all rows are fetched. You also have to fetch all result
rows from an unbuffered SQL query before you can send a new SQL query to MySQL, using
the same link_identifier.
The Model-View-Control (MVC) pattern, originally formulated in the late 1970s, is a software
architecture pattern built on the basis of keeping the presentation of data separate from the
methods that interact with the data. In theory, a well-developed MVC system should allow a
front-end developer and a back-end developer to work on the same system without interfering,
sharing, or editing files either party is working on.
Even though MVC was originally designed for personal computing, it has been adapted and is
widely used by web developers due to its emphasis on separation of concerns, and thus
indirectly, reusable code. The pattern encourages the development of modular systems, allowing
developers to quickly update, add, or even remove functionality.
In this article, I will go the basic principles of MVC, a run through the definition of the pattern
and a quick example of MVC in PHP. This is definitely a read for anyone who has never coding
with MVC before or those wanting to brush up on previous MVC development skills.
Understanding MVC
The pattern’s title is a collation of its three core parts: Model, View, and Controller. A visual
representation of a complete and correct MVC pattern looks like the following diagram:
The image shows the single flow layout of data, how it’s passed between each component, and
finally how the relationship between each component works.
Model:
The Model is the name given to the permanent storage of the data used in the overall design. It
must allow access for the data to be viewed, or collected and written to, and is the bridge
between the View component and the Controller component in the overall pattern.
`
One important aspect of the Model is that it’s technically “blind” – by this I mean the model has
no connection or knowledge of what happens to the data when it is passed to the View or
Controller components. It neither calls nor seeks a response from the other parts; its sole purpose
is to process data into its permanent storage or seek and prepare data to be passed along to the
other parts.
The Model, however, cannot simply be summed up as a database, or a gateway to another system
which handles the data process. The Model must act as a gatekeeper to the data itself, asking no
questions but accepting all requests which comes its way. Often the most complex part of the
MVC system, the Model component is also the pinnacle of the whole system since without it
there isn’t a connection between the Controller and the View.
View:
The View is where data, requested from the Model, is viewed and its final output is determined.
Traditionally in web apps built using MVC, the View is the part of the system where the HTML
is generated and displayed. The View also ignites reactions from the user, who then goes on to
interact with the Controller. The basic example of this is a button generated by a View, which a
user clicks and triggers an action in the Controller.
There are some misconceptions held about View components, particularly by web developers
using the MVC pattern to build their application. For example, many mistake the View as having
no connection whatsoever to the Model and that all of the data displayed by the View is passed
from the Controller. In reality, this flow disregards the theory behind the MVC pattern
completely. Fabio Cevasco’s article The CakePHP Framework: Your First Bite demonstrates this
confused approach to MVC in the CakePHP framework, an example of the many non-traditional
MVC PHP frameworks available:
“It is important to note that in order to correctly apply the MVC architecture, there must
be no interaction between models and views: all the logic is handled by controllers“
Furthermore, the description of Views as a template file is inaccurate. However, as Tom Butler
points out, this is not one person’s fault but a multitude of errors by a multitude of developers
which result in developers learning MVC incorrectly. They then go on to educate others
incorrectly. The View is really much more than just a template, however modern MVC inspired
frameworks have bastardised the view almost to the point that no one really cares whether or not
a framework actually adheres to the correct MVC pattern or not.
It’s also important to remember that the View part is never given data by the Controller. As I
mentioned when discussing the Model, there is no direct relationship between the View and the
Controller without the Model in between them.
`
Controller
The final component of the triad is the Controller. Its job is to handle data that the user inputs or
submits, and update the Model accordingly. The Controller’s life blood is the user; without user
interactions, the Controller has no purpose. It is the only part of the pattern the user should be
interacting with.
The Controller can be summed up simply as a collector of information, which then passes it on to
the Model to be organized for storage, and does not contain any logic other than that needed to
collect the input. The Controller is also only connected to a single View and to a single Model,
making it a one way data flow system, with handshakes and signoffs at each point of data
exchange.
It’s important to remember the Controller is only given tasks to perform when the user interacts
with the View first, and that each Controller function is a trigger, set off by the user’s interaction
with the View. The most common mistake made by developers is confusing the Controller for a
gateway, and ultimately assigning it functions and responsibilities that the View should have
(this is normally a result of the same developer confusing the View component simply as a
template). Additionally, it’s a common mistake to give the Controller functions that give it the
sole responsibility of crunching, passing, and processing data from the Model to the View,
whereas in the MVC pattern this relationship should be kept between the Model and the View.
MVC in PHP:
It is possible to write a web application in PHP whose architecture is based on the MVC pattern.
Let’s start with a bare bones example:
<?php
class Model
{
public $string;
<?php
$model = new Model();
$controller = new Controller($model);
$view = new View($controller, $model);
echo $view->output();
As you can see in the example above, we don’t have any Controller-specific functionality
because we don’t have any user interactions defined with our application. The View holds all of
the functionality as the example is purely for display purposes.
Let’s now expand the example to show how we would add functionality to the controller, thereby
adding interactivity to the application:
<?php
class Model
{ public $string;
<?php
$model = new Model();
$controller = new Controller($model);
$view = new View($controller, $model);
echo $view->output();