Integrate database with a website
Integrate database with a website
Database
HTML
CSS PHP SQL
JS
11/14/2023 Tekalegn B.
Database
Database is collection of interrelated data. Data is known facts
that can be recorded and that have implicit meaning. E.g. names,
telephone numbers, courses you take, address of peoples you
know.
11/14/2023 Tekalegn B.
Database is just a computerized record keeping system or a
kind of electronic filing cabinet. Database is a repository for
collection of computerized data files.
Database is a shared collection of logically related data
designed to meet the information needs of an
organization. Since it is a shared corporate resource, the
database is integrated with minimum amount of or no
duplication.
11/14/2023 Tekalegn B.
Data Definition Language (DDL)
Allows user to describe and name entitles, attributes and
relationships required for the application.
– Used to define the database schema
The language is used to create database, tables, alter them,
etc.
With this, you can also rename the database, or drop them.
It specifies the database schema. The DDL statements
include
• CREATE: Create new database, table, etc.
• ALTER: Alter(changes) existing database, table, etc.
• DROP: Drop or delete the database
• RENAME: Set a new name for the table.
11/14/2023 Tekalegn B.
Data Manipulation Language (DML)
– Language for accessing and manipulating the data
organized by the appropriate data model, Some times
called query language.
• The language used to manipulate the database like
inserting data, updating table, retrieving record from a
table, etc. is known as Data Manipulation Language −
• SELECT: Retrieve or extract data from the database
• INSERT: Insert a new data in to a database table
• UPDATE: Update data in a database table
• DELETE: Delete deletes a database table
Procedural DML:
– user specifies what data is required & how to get the data.
Non-Procedural DML:
– user specifies what data is required but not how it is to be
retrieved.
11/14/2023 Tekalegn B.
Data Control Language(DDL)
Grant privilege to a user using the GRANT statement. In
the same way, revoke the privilege using the REVOKE
statement. Both of these statements come under the Data
Control Language (DCL). −
• GRANT: Give privilege to access the database.
• REVOKE: Take back the privilege to access the database.
11/14/2023 Tekalegn B.
Transaction Control Language
Manage transactions in the Database using the Transaction
Control Language:-
• COMMIT: Save the work.
• SAVEPOINT: Set a point in transaction to rollback later
• ROLLBACK: Restores since last commit
11/14/2023 Tekalegn B.
Server Side Scripting Language
11/14/2023 Tekalegn B.
Web –servers
11/14/2023 Tekalegn B.
Web page is a document typically written in HTML that
is almost always accessible via HTTP or pages on which
information is displayed on the web. It can be Static or
dynamic web page.
Static web page means that what is displayed does not
change until the underlying HTML or XML is changed.
11/14/2023 Tekalegn B.
Scripting Language is a programming language in a
simple text format. Generally, code written in a scripting
language does not have to compiled- unlike, for example,
code written in C++ or Visual basic. Instead , it is
interpreted at the time of execution. Web browsers can
interpret certain scripting language.
11/14/2023 Tekalegn B.
There are different languages in computer world. These may:
Client Side script Language(html, css and JavaScript)
Server side script Language(html (php, ASP.NET, java,
ColdFusion, Perl, Ruby, Go, Python, and server-side JavaScript.)
Client-side Script is executed on the client, by the browser.
Server side Scripting Language is executed on the server.
ASP---Active Server Pages
JSP---java via java Server pages
Php---hyper text Preprocessors
11/14/2023 Tekalegn B.
Server-side Scripting
Server side scripting is a web server technology in which a user’s
request is fulfilled by running a script directly on the web server to
generate dynamic web pages.
It is usually used to provide interactive web sites that interface to
database or other data stores.
The primary advantage of server-side scripting is the ability to high
customize the response based on the user’s requirements, access
rights, or queries into data stores.
Server-side web scripting is mostly about connecting websites to
back end servers, such as databases. This enables two-way
communication:
i. Client to Server: customer-enter information as request
ii. Server to Client: Web pages can be assembled from back end-
server to give output.
11/14/2023 Tekalegn B.
What is PHP?
PHP stands for hyper text preprocessor and is a server-
side language. This means that the script is run on your
web server , not on the user’s browser, so you do not need
to worry about compatibility issues.
PHP support many databases (MySQL, Informix, oracle,
Sybase, solid, PostgreSQL, Generic ODBC, Microsoft
SQL Server etc.).
PHP files can contain text, HTML tags and scripts. Like
others files written in server side language. PHP files are
returned to the browsers as plain HTML and it has a file
extension of “.php”, “.php3”, or “.phtml”.
11/14/2023 Tekalegn B.
Why PHP?
Allows easy storage and retrieval of information from
supported database
Accessibility: You can reach the internet from any
browsers, any device, any time, anywhere.
Manageability: It does not require distribution of
application code and it is easy to change code.
Security: The source code is not exposed. Once user is
authenticated , can only allow certain actions. It also
allows encryption.
Scalability: Web-based 3-tier architecture can scale out.
11/14/2023 Tekalegn B.
What you need to get started?
Hopefully you have established a basic idea of what server-side
scripting is , and when you should use it. Next you need some basic
requisites to be able to write and execute scripts. Basically you need:
1. First for all you need a computer with a web server installed. PHP
uses web servers such as Apache, IIS etc. But for this course we will
install WAMPP or XAMPP servers. WAMPP server refers to a
software stack for the Microsoft windows operating system, created
by Romain Bourdon and consisting of the apache web server,
OpenSSL for SSL(Secure Socket Layer) Support , MySQL database
and PHP programming language.
WAMPP server has a root directory called WWW. So all the files of a
website must be stored under this directory (C:\wampp\www) to be
executed by the server.
2. You need some sort of text editor such as Notepade, Notepade++,
etc. to write the script.
11/14/2023 Tekalegn B.
3. You also need a web browser to display the web content.
The web browser can be internet explorer, Mozilla firefox ,
Opera, and Google Chrome etc.
Generally, to connect the database with a website first we must
follow the following steps.
1. First download and install XAMPP or WAMPP server software's
2. Create a database inside XAMPP or WAMPP
3. Download and install text editors(sublime text, notepad++..)
4. Write a PHP file and save as .php and connect with database
11/14/2023 Tekalegn B.
PHP(Hyper text Preprocessor)
11/14/2023 Tekalegn B.
PHP file or code differentiate from other elements in the page by php parsing engine.
The mechanism for doing so is known as ‘escaping to php’. There are four ways to do
this:
I. Canonical PHP tags: the most universally effective PHP tag style
<?php
Your php code here
?>
II. Short-open(SGML-style) tags: short or short-open tags looks like
<?
Your php code here
?>
III. ASP-style tags: mimic the tags used by Active Server page to delineate code blocks.
<%
Your php code here
%>
IV. HTML Script tags: HTML script tags look like this
<script language=“PHP”>
Your php code here
</script>
11/14/2023 Tekalegn B.
PHP Output Statements
PHP has different syntaxes but for maximum compatibility , it is recommended
to use the canonical style or <?php ?> this.
Each code line in PHP must end with a semicolon(;). The semicolon is a
separator and is used to distinguish one set of instructions from another.
There are two basic statements to output text with PHP: that are echo and print .
ECHO PRINT
Echo has no return value Print has return value
Echo takes Multiple parameters. Print takes only one argument.
Echo is marginally faster than print Print is marginally slower than echo
Syntax: Syntax:
echo outputstament; or print outputstament; or
echo (outputstament); print(outputstament);
Example: Example:
echo “Hello World!!”; print “Hello World!!”;
echo (“Hello World!!”); print (“Hello World!!”);
Return value means whether the print statement is succeeded or not. If the print
statement succeeded, the statement returns 1 otherwise 0.
Error: echo Hello World; because string should be enclosed in quotes.
11/14/2023 Tekalegn B.
Connecting to Databases
• One of the reasons for PHP’s popularity as a web scripting language is its
support for a wide range of relational database system. This support makes it
easy for web developers to create data-driven web-sites and to prototype new
web applications quickly and efficiently.
• PHP supports more than fifteen different database engines, including Microsoft
SQL server, IBM DB2, PostgreSQL, MySQL, and Oracle. Using database in
application s helps us to: Read/Write data, Store More data, have better
organized data, faster access to data, easier to manipulate and relate data to other
data.
• Database is a collection (set ) of tables. We should have 1database for 1
application.
• Tables: is a set of rows and columns. It represents a single concept such as
product, customers, order etc. we can create relationship among tables.
• Columns: a set of data of single data type. Example FirstName, LastName,
Email, Password etc. . Columns have types such as strings, integers, float, date
etc.
11/14/2023 Tekalegn B.
• Rows: is a single record of data. Example “Abebe”, “Kebede”,
[email protected].
• Fields: is the intersection of rows and column. E.g. FirstName: “Abebe”
• Index: Data structure on a table to increase look up speed.
• Foreign Key: table columns whose values references rows in another
table. It is the foundation of relational table.
• Primary Key: is a unique key of the table. It is not occur twice in one
table
PHP allows developers to interact with databases in two ways:
1. By using a customized database specific extension
2. By using the database neural PHP Data Objects(PDO)extension
While the PDO extension is more portable, many developers still find it
preferable to use the native database extensions, especially when the native
extension offers better performance or more features than the PDO version.
Of the various database engines supported by PHP, the most popular one by
far is MySQL. Both PHP and MySQL are open-source.
11/14/2023 Tekalegn B.
Connect to MySQL server/Existing Database
PHP provides us different APIs(Application Program Interfaces) to deal
with MySQL server databases. These are:
mysql ( original MySQL)
mysqli (MySQL improved)
PDO (PHP data object)
The difference between these APIs are shown on the table given below.
Features mysql mysqli PDO
Introduced V2.0 V5.0 V5.1
Deprecated V5.5 - -
Included with PHP yes yes Yes
Pre-configured for MySQL yes yes
Other database supported Yes
Procedural Interface yes yes
Object-oriented interface Yes Yes
Prepare statements yes Yes
11/14/2023 Tekalegn B.
PHP database interactions in five steps:
Create a database connection
Perform Database query
Use returned data if any
Release returned data
Close database connection
Creating a database connection
Before we enable do anything with MySQL in PHP , we should first connect
to the MySQL server using specific connection variables. Connection
variables consist of the following common parameters, of which the first
one is required while others are optional;-
Host name: this is the name of the server. We can change to whatever
host is acting as MySQL server.
User name: the root user of the system
User name’s password: this is encrypted written with the form for
security.
11/14/2023 Tekalegn B.
The common function in PHP that uses for server connection is mysql_connect() or
mysqli_connect() function.
The General syntax of database connection in mysqli is as follow:
connection.php
connection.php
<?php
<?php
$server=“localhost”;
$server="localhost";
$dbuser=“root”;
$dbuser="root";
$dbpassword=“”;
$dbpassword="";
$dbname=“test”;
$dbname="student";
$conn=mysqli_connect($server, $dbuser,
$conn=mysqli_connect($server, $dbuser,
$dbpassword, $dbname);
$dbpassword, $dbname);
if (!$conn)
if (!$conn)
{
{
die("connection failed:".mysqli_connect_error);
die("connection
}
failed:".mysqli_connect_error);
}
$sql="CREATE DATABASE loginpage";
if(mysqli_query($conn, $sql))
echo "The database connected successfuly!!";
echo "The databses creaed successfuly!!";
mysqli_close($conn)
else
?>
echo "error creating a
database".$mysqli_error;
//This connection used when we already
Mysqli_close($conn)
created adatabse
?>
11/14/2023 Tekalegn B.
PHP & MySQL
• PHP will work with virtually all database software, including Oracle and Sybase
but most commonly used is freely available MySQL database which is released
under an open-source license. So you have nothing to pay to use it.
• MySQL is a fast, easy-to-use RDBMS used being used for many small and big
businesses.
• MySQL is developed, marketed, and supported by MySQL AB, which is a
Swedish company.
• MySQL is a very powerful program in its own right. It handles a large subset of
the functionality of the most expensive and powerful database packages.
• MySQL uses a standard form of the well-known SQL data language.
• MySQL is becoming so popular because of many good reasons.
– MySQL works on many operating systems and with many languages including PHP, PERL, C,
C++, JAVA, etc.
– MySQL works very quickly and works well even with large data sets.
– MySQL is very friendly to PHP, the most appreciated language for web development.
– MySQL supports large databases, up to 50 million rows or more in a table. The default file size
limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a
theoretical limit of 8 million terabytes (TB).
11/14/2023 Tekalegn B.
PHP & MySQL Cont...
• MySQL is customizable. The open source GPL (General Public License )
license allows programmers to modify the MySQL software to fit their
own specific environments.
• PHP provides various functions to access MySQL database and to
manipulate data records inside MySQL database.
• You would require to call PHP functions in the same way you call any
other PHP function.
• The PHP functions for use with MySQL have the following general
format:
mysql_function(value,value,...);
• The second part of the function name is specific to the function, usually a
word that describes what the function does. The following are two of the
functions which we will use in our lesson.
mysqli_connect($connect);
mysqli_query($connect,"SQL statement");
11/14/2023 Tekalegn B.
PHP & MySQL cont...
Following example shows a generic syntax of PHP to call any MySQL
function.
<html><head><title>PHP with MySQL</title></head>
<body>
<?php
$retval = mysql_function(value, [value,...]);
if( !$retval )
{
die ( "Error: a related error message" );
}
// Otherwise MySQL or PHP Statements
?>
</body></html>
11/14/2023 Tekalegn B.
Important Functions in PHP
There are different functions in PHP that have different purposes.
These are:
mysqli_connect($server, $user, $password, $databasename);
mysqli_select_db($connection, “database name”): Equivalent to
the MySQL command USE; makes the selected database the
active one.
mysqli_query($connection, "query”): used to send any type of
MySQL command to the server.
mysqli_fetch_rows(“results variable from query): used to return
a rows of the entire results of a database query.
mysqli_fetch_array(“results variable from query): used to
return several rows of the entire results of a database query.
mysqli_free_result(“result variable from query”): used to
release the returned results.
mysqli_error(): shows the error message that has been returned
directly from the MySQL Tekalegn
11/14/2023 server.
B.
The Important MySQL Functionality Along With
PHP: MySQL Connection Using PHP Script:
• PHP provides mysql_connect() function to open a database
connection.
• This function takes five parameters and returns a MySQL link
identifier on success, or FALSE on failure.
Syntax:
– connection
mysqli_connect(server, user, passwd);
• server
– Optional - The host name running database server. If not specified then default
value is localhost:3036.
• user
– Optional - The username accessing the database. If not specified then default
is the name of the user that owns the server process.
• passwd
– Optional - The password of the user accessing the database. If not specified
then default is an empty password.
– Note: There are more available parameters, but the ones listed above are the most
important.
11/14/2023 Tekalegn B.
Closing a connection
• You can disconnect from MySQL database anytime using another PHP function
mysqli_close().
• This function takes a single parameter which is a connection returned by
mysqli_connect() function.
Syntax:
bool mysqli_close ( resource $link_identifier );
– If a resource is not specified then last opened database is closed.
– This function returns true if it closes connection successfully otherwise it returns
false.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
Create Database using PHP Script:
11/14/2023 Tekalegn B.
Example to create a database:
<html><head><title>Creating MySQL Database</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'CREATE DATABASE TUTORIALS';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create database: ' . mysql_error());
}
echo "Database TUTORIALS created successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
</body></html>
Drop Database using PHP Script:
11/14/2023 Tekalegn B.
Example to delete a database:
<html><head><title>Deleting MySQL Database</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
Warning
if(! $conn ) •While deleting a database using
{ PHP script, it does not prompt
die('Could not connect: ' . mysql_error()); you for any confirmation.
} •So be careful while deleting a
echo 'Connected successfully<br />'; MySQL database.
$sql = 'DROP DATABASE TUTORIALS'; •Once you get connection with
$retval = mysql_query( $sql, $conn ); MySQL server, it is required to
if(! $retval )
select a particular database to
{
die('Could not delete database: ' . mysql_error());
work with.
} • This is because there may be
echo "Database TUTORIALS deleted successfully\n"; more than one database available
mysql_close($conn); with MySQL Server.
?>
</body></html>
11/14/2023 Tekalegn B.
Selecting MySQL Database Using PHP Script:
11/14/2023 Tekalegn B.
Numeric Data Types
• INT - A normal-sized integer that can be signed or unsigned. If signed, the
allowable range is from -2147483648 to 2147483647. If unsigned, the
allowable range is from 0 to 4294967295. You can specify a width of up to
11 digits.
• TINYINT - A very small integer that can be signed or unsigned. If signed,
the allowable range is from -128 to 127. If unsigned, the allowable range is
from 0 to 255. You can specify a width of up to 4 digits.
• SMALLINT - A small integer that can be signed or unsigned. If signed, the
allowable range is from -32768 to 32767. If unsigned, the allowable range
is from 0 to 65535. You can specify a width of up to 5 digits.
• MEDIUMINT - A medium-sized integer that can be signed or unsigned. If
signed, the allowable range is from -8388608 to 8388607. If unsigned, the
allowable range is from 0 to 16777215. You can specify a width of up to 9
digits.
• BIGINT - A large integer that can be signed or unsigned. If signed, the
allowable range is from -9223372036854775808 to
9223372036854775807. If unsigned, the allowable range is from 0 to
18446744073709551615.
11/14/2023 You canTekalegn
specify
B. a width of up to 11 digits.
Numeric Data Types cont…
• FLOAT(M,D) - A floating-point number that cannot be unsigned.
You can define the display length (M) and the number of decimals
(D). This is not required and will default to 10,2, where 2 is the
number of decimals and 10 is the total number of digits (including
decimals). Decimal precision can go to 24 places for a FLOAT.
• DOUBLE(M,D) - A double precision floating-point number that
cannot be unsigned. You can define the display length (M) and the
number of decimals (D). This is not required and will default to 16,4,
where 4 is the number of decimals. Decimal precision can go to 53
places for a DOUBLE. REAL is a synonym for DOUBLE.
• DECIMAL(M,D) - An unpacked floating-point number that cannot
be unsigned. In 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.
11/14/2023 Tekalegn B.
The MySQL date and time data types are:
11/14/2023 Tekalegn B.
The table creation command requires:
• Name of the table
• Names of fields
• Definitions for each field
Syntax:
• Here is generic SQL syntax to create a MySQL table:
– CREATE TABLE table_name (column_name column_type);
• tutorials_tbl( tutorial_id INT NOT NULL AUTO_INCREMENT, tutorial_title
VARCHAR(100) NOT NULL, tutorial_author VARCHAR(40) NOT NULL,
submission_date DATE, PRIMARY KEY ( tutorial_id ));
Here few items need explanation:
• Field Attribute NOT NULL is being used because we do not want this field to
be NULL. SO if user will try to create a record with NULL value then MySQL
will raise an error.
• Field Attribute AUTO_INCREMENT tells to MySQL to go ahead and add the
next available number to the id field.
• Keyword PRIMARY KEY is used to define a column as primary key. You can
use multiple columns separated by comma to define a primary key.
11/14/2023 Tekalegn B.
Creating Tables Using PHP Script:
• To create new table in any existing database you would need to use PHP function
mysql_query().
• You will pass its second argument with proper SQL command to create a table.
Example:
<html><head> <title>Creating MySQL Tables</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
11/14/2023 Tekalegn B.
cont…
11/14/2023 Tekalegn B.
Insert.html
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
11/14/2023 Tekalegn B.
Insert.php
<?php
$con=mysqli_connect(““, ““ , ““ , "my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " .
mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
11/14/2023
mysqli_close($con); Tekalegn B.
?>
Fetching Data
• The SQL SELECT command is used to fetch data from MySQL database.
• Here is generic SQL syntax of SELECT command to fetch data from
MySQL table:
SELECT field1, field2,...fieldN table_name1, table_name2...[WHERE
Clause][OFFSET M ][LIMIT N]
• You can use one or more tables separated by comma to include various
condition using a WHERE clause. But WHERE clause is an optional part
of SELECT command.
• You can fetch one or more fields in a single SELECT command.
• You can specify star (*) in place of fields. In this case SELECT will return
all the fields.
• You can specify any condition using WHERE clause.
• You can specify an offset using OFFSET from where SELECT will start
returning records. By default offset is zero
• You can limit the number of returned
11/14/2023
using LIMIT attribute.
Tekalegn B.
Fetching Data Using PHP Script:
11/14/2023 Tekalegn B.
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error()); }
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Tutorial ID :{$row['tutorial_id']} <br> ". "Title:
{$row['tutorial_title']} <br> ". "Author:
{$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "-----------------------
---------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
• The content of the rows are assigned to the variable $row
and the values in row are then printed.
• NOTE: Always remember to put curly brackets when you
want to insert an array value directly into a string.
• In above example the constant MYSQL_ASSOC is used as
the second argument to PHP function mysql_fetch_array(),
so that it returns the row as an associative array.
• With an associative array you can access the field by using
their name instead of using the index.
• PHP provides another function called mysql_fetch_assoc()
which also returns the row as an associative array.
11/14/2023 Tekalegn B.
Example:
• Try out the following example to display all the
records from tutorial_tbl table using
mysql_fetch_assoc() function.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser,
$dbpass);
If(! $conn )
{ die('Could not connect: ' . mysql_error());}
11/14/2023 Tekalegn B.
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author,
submission_date FROM tutorials_tbl';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_assoc($retval))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ". "Author:
{$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "-------------------
<br>";}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
• You can also use the constant MYSQL_NUM, as the second
argument to PHP function mysql_fetch_array().
• This will cause the function to return an array with numeric
index.
Example:
• Try out following example to display all the records from
tutorials_tbl table using MYSQL_NUM argument.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error()); }
11/14/2023 Tekalegn B.
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date FROM
tutorials_tbl';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval,
MYSQL_NUM))
{ echo "Tutorial ID :{$row[0]} <br> ". "Title:
{$row[1]} <br> ". "Author: {$row[2]} <br> ".
"Submission Date : {$row[3]} <br> ". "-------
<br>";}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
All the above three examples
11/14/2023 Tekalegn B. will produce same result.
Releasing Memory:
• Its a good practice to release cursor memory at the end of
each SELECT statement.
• This can be done by using PHP function
mysql_free_result().
• Below is the example to show how it has to be used.
Example:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
11/14/2023 Tekalegn B.
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date FROM
tutorials_tbl';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval, MYSQL_NUM))
{ echo "Tutorial ID :{$row[0]} <br> ". "Title:
{$row[1]} <br> ". "Author: {$row[2]} <br> ".
"Submission Date : {$row[3]} <br> ". "-------
<br>";}
mysql_free_result($retval);
echo "Fetched data successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
Using WHERE clause
Following example will return all the records from tutorials_tbl table
for which author name is Sanjay:
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date FROM tutorials_tbl
WHERE tutorial_author="Sanjay"';
11/14/2023 Tekalegn B.
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval,
MYSQL_ASSOC))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ". "Author:
{$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "--------------
<br>";}
echo "Fetched data successfully\n";
mysql_close($conn);
11/14/2023 ?> Tekalegn B.
Updating data
• There may be a requirement where existing data in a
MySQL table need to be modified.
• You can do so by using SQL UPDATE command.
• This will modify any field value of any MySQL table.
Syntax:
• Here is generic SQL syntax of UPDATE command to
modify data into MySQL table:
UPDATE table_name SET field1=new-value1, field2=new-
value2[WHERE Clause]
• You can update one or more field all together.
• You can specify any condition using WHERE clause.
• You can update values in a single table at a time.
• The WHERE clause is very useful when you want to
update selected rows in a table.
11/14/2023 Tekalegn B.
Updating Data Using PHP Script:
• You can use SQL UPDATE command with or
without WHERE CLAUSE into PHP function
mysql_query().
• Try out following example to update
tutorial_title field for a record having tutorial_id
as 3.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
11/14/2023
{ die('Could not connect:
Tekalegn B.
' . mysql_error());}
$sql = 'UPDATE tutorials_tbl SET
tutorial_title="Learning JAVA" WHERE
tutorial_id=3';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not update data: ' . mysql_error());}
echo "Updated data successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
Deleting data
11/14/2023 Tekalegn B.
Deleting Data Using PHP Script:
11/14/2023 Tekalegn B.
$sql = 'DELETE FROM tutorials_tbl
WHERE tutorial_id=3';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not delete data: ' . mysql_error());}
echo "Deleted data successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
• We have seen SQL SELECT command to fetch data from MySQL
table.
• We can also use a conditional clause called WHERE clause to
select required records.
• A WHERE clause with equal sign (=) works fine where we want to
do an exact match.
• Like if "tutorial_author = 'Sanjay'". But there may be a requirement
where we want to filter out all the results where tutorial_author
name should contain "jay".
• This can be handled using SQL LIKE clause along with WHERE
clause.
• If SQL LIKE clause is used along with % characters then it will
work like a meta character (*) in Unix while listing out all the files
or directories at command prompt.
• Without a % character LIKE clause is very similar to equal sign
along with WHERE clause.
11/14/2023 Tekalegn B.
Using LIKE clause
11/14/2023 Tekalegn B.
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval,
MYSQL_ASSOC))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ". "Author:
{$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "-------------
<br>";}
echo "Fetched data successfully\n";
mysql_close($conn);
11/14/2023 Tekalegn B.
?>
Using ORDER BY clause
• We have seen SQL SELECT command to fetch data from MySQL table.
• When you select rows, the MySQL server is free to return them in any
order, unless you instruct it otherwise by saying how to sort the result.
• But you sort a result set by adding an ORDER BY clause that names the
column or columns you want to sort by.
Syntax:
• Here is generic SQL syntax of SELECT command along with ORDER BY
clause to sort data from MySQL table:
SELECT field1, field2,...fieldN table_name1, table_name2...ORDER BY
field1, [field2...] [ASC [DESC]]
• You can sort returned result on any field provided that filed is being listed
out.
• You can sort result on more than one field.
• You can use keyword ASC or DESC to get result in ascending or
descending order. By default its ascending order.
• You can use WHERE...LIKE clause in usual way to put condition.
11/14/2023 Tekalegn B.
Using ORDER BY clause inside PHP Script:
• You can use similar syntax of ORDER BY clause into PHP function
mysql_query().
• This function is used to execute SQL command and later another PHP
function mysql_fetch_array() can be used to fetch all the selected data.
• Try out following example which returns result in descending order of
tutorial author.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser,
$dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
11/14/2023 Tekalegn B.
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date FROM tutorials_tbl
ORDER BY tutorial_author DESC';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ".
"Title: {$row['tutorial_title']} <br> ". "Author:
{$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "----------------
<br>";}
echo "Fetched data successfully\n";
11/14/2023
mysql_close($conn); Tekalegn B.
?>
Handling NULL Values
• We have seen SQL SELECT command along with WHERE
clause to fetch data from MySQL table. But when we try to
give a condition which compare field or column value to
NULL it does not work properly.
• To handle such situation MySQL provides three operators
– IS NULL: operator returns true of column value is NULL.
– IS NOT NULL: operator returns true of column value is not
NULL.
– <=> operator compare values, which (unlike the = operator) is true
even for two NULL values
– Conditions involving NULL are special. You cannot use = NULL
or != NULL to look for NULL values in columns. Such
comparisons always fail because it's impossible to tell whether or
not they are true. Even NULL = NULL fails.
• To look for columns that are or are not NULL, use IS NULL
or IS NOT NULL.
11/14/2023 Tekalegn B.
Handling NULL Values in PHP Script:
• You can use if...else condition to prepare a query based on NULL value.
• Following example take tutorial_count from outside and then compare it
with the value available in the table.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
if( isset($tutorial_count ))
{ $sql = 'SELECT tutorial_author, tutorial_count
FROM tcount_tbl WHERE tutorial_count =
$tutorial_count';}else{ $sql = 'SELECT
tutorial_author, tutorial_count FROM tcount_tbl
WHERE tutorial_count IS $tutorial_count';}
11/14/2023 Tekalegn B.
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Author:{$row['tutorial_author']} <br> ". "Count:
{$row['tutorial_count']} <br> ". "-----------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
11/14/2023 Tekalegn B.
Database
HTML
CSS PHP SQL
JS
END
THANK
YOU!!!!!!
11/14/2023 Tekalegn B.