0% found this document useful (0 votes)
43 views46 pages

3 Chapter Edit

The document discusses database concepts and interactions with PHP. It explains how to connect to a database, create and select a database, build tables, and close connections. Key aspects covered include using MySQLi functions to connect, query the database, retrieve and release data, and close connections.

Uploaded by

adisuadmasu42
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views46 pages

3 Chapter Edit

The document discusses database concepts and interactions with PHP. It explains how to connect to a database, create and select a database, build tables, and close connections. Key aspects covered include using MySQLi functions to connect, query the database, retrieve and release data, and close connections.

Uploaded by

adisuadmasu42
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Chapter : Three

Manipulating Databases with PHP

• One of the reasons for PHP’s popularity as a Web scripting language is its
(cross-platform, compatible, scalability, Allows for various DBs …. etc)

• Allows for various DB formats (Microsoft SQL Server, IBM DB2,


PostgreSQL, MySQL, and Oracle. )

• Makes it easy for Web developers to create Web applications quickly and
efficiently.
Database Access in PHP

• Database: is a separate application that stores a collection of data.

• Table: is a set of rows and columns. It represents a single concept such as


products.

• Column: a set of data of single data type. Ex. FirstName, LastName,

• Row: single record of data. Ex. “Abebe”, “Kebede”,

• Field: is the intersection of a row and a column. Ex. FirstName: ”Abebe”

• Redundancy: Storing data twice, redundantly to make the system faster.


Cont.…
• Primary Key: is unique a key value can not occur twice in one table.

• Foreign Key: A foreign key is the linking pin between two tables.

• Compound Key: (composite key) is a key that consists of multiple columns,


because one column is not sufficiently unique.

• Referential Integrity: Referential Integrity makes sure that a foreign key value
always points to an existing row.

• Entity Integrity :???


MySQL Database:

• 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).
Database Interactions

 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 database in PHP, we should first connect


to the MySQL server using specific connection variables.

• Connection variables consist of the following common parameters.

• Host name: This is the name of the server. We can change to whatever host
is acting as MySQL server. It is optional (localhost).

• User name: The root user of the system. It is require (root).

• User’s password:-This is encrypted written with the form for security. It is


require (” “);
Cont.…

• The common function in PHP that uses for server connection is


mysql_connect( ) or mysqli_connect() function.

• This function has the following syntax:- mysqli_connect ("hostname",


"user", "pass") to connect with MySQL server.

• PHP provides mysqli_connect function to open a database connection. This


function can take up to five parameters and returns a MySQL link identifier
on success, or FALSE on failure.

• The five parameters are the three above and the two below options.
Cont.…
• new_link Optional - If a second call is made to mysqli_connect() with the same arguments,
no new connection will be established; instead, the identifier of the already opened
connection will be returned.
• client_flags Optional - A combination of the following constants:
MYSQL_CLIENT_SSL - Use SSL encryption
MYSQL_CLIENT_COMPRESS - Use compression protocol
MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names
MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds
of inactivity before closing the connection
• Note: There are more available parameters, but the ones listed above are the most
important.
Databaseconnection.php
• <?php
• $dbhost = “localhost”; Optional – you can placed “”, but you couldn’t
placed any char. if data base (DB) name doesn't exit it will be optional.
• $dbuser = 'root'; Require, Warning: Access denied for user
''@'localhost' to database “aip”, ,if data base (DB) name doesn't exit it will be
optional.
• $dbpass = “"; Require, Access denied for user 'root'@'localhost'
(using password: YES)
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass,“Aip");
• if(! $conn )
• {
• die('Could not connect: ' . mysqli_error()); }
• echo 'Connected successfully';
• ?>
Databaseconnection.php
Closing a DB 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:

mysql_close ( resource $link_identifier );

mysqli_close($conn); or mysql_close($conn);

• This function returns true if it closes connection successfully otherwise it returns


false.
Closing a DB connection
•<?php
•$host='localhost'; // can you change the order of variable with their value?
•$user='root';
•$pas='';
•$conn = mysqli_connect($host, $user, $pass); //can you change the order of
parameters ?
• if(! $conn )
•{
• die('Could not connect: ' . mysqli_error());
•}
• echo 'Connected successfully';
•mysqli_close($conn); // Don’t use this function in DB connection.
•Create database

• $sqli = "CREATE DATABASE GCS";


Creating the working Database

• After establishing a MySQL connection with the code above, you then need to
choose which database you will be using with this connection.

• If the database you are looking to work on is not available, you can create it using
mysqli_query() or mysql_query() function together with CREATE command
followed by database name.

• mysqli_query function can take two parameters and returns TRUE on success or
FALSE on failure.

• The parameters are:- sqli and connection.


Cont..

• The syntax of the function is:-

• mysql_query(sql, connection variable); or

• mysqli_query(connection variable,sql);

• To create a database uses the following sql syntax:

• CREATE DATABASE database_name

• mysql_query ("create database test”,$connection): told MySQL to create a


database called test.
Cont..
• die(mysqli_error()); will print out an error if there is a problem in the
database creation process.

• Closing Query

• When you are finished working with query results retrieved with the
mysqli_query() function, use the mysqli_free_result() function to close the
result set

• To close the result set, pass to the mysqli_free_result() function the variable
containing the result pointer from the mysqli_query() function
Creating the working Database
Creating the working Database
Recommended
• Use database connection and database creation at one file extension.
Cont.…
• There are also functions in PHP which have different purposes. For instance,

• mysql_select_db("database name") or
mysqli_select_db(“connection”,"database name") : Equivalent to the
MySQL command USE; makes the selected database the active one.

• mysqli_query("query"): Used to send any type of MySQL command to the


server.

• mysqli_fetch_rows("results variable from query"): Used to return a row of


the entire results of a database query.
Cont.…

• mysqli_affected_rows():Print out affected rows from different queries:

• mysql_fetch_array("results variable from query"): Used to return several


rows of the entire results of a database query.

• mysql_free_result(“result variable from query”): Used to release the


returned results.

• mysql_error(): Shows the error message that has been returned directly from
the MySQL server.
Drop Database

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn)
{
die('Could not connect: ' . mysqli_error());
}
echo "Connected successfully"."<br>" ;
Drop Database..
$sqli= 'DROP DATABASE AIP';
$retval = mysqli_query($conn,$sqli);
if(! $retval )
{
die('Could not delete database: ' . mysqli_error($conn));
}
echo "Database AIP deleted successfully";
mysqli_close($conn);
?>
Create Table MySQL
• Before you enter data (rows) into a table, you must first define what kinds of
data will be stored (columns).This can be done using Create sql statement.

• A database table has its own unique name and consists of columns and rows.

• Syntax:

• CREATE TABLE table_name (column_name1 data_type,column_name2


data_type,....)

• We are now going to design a MySQL query to summon our table from
database test.
Create Table Cont..
• <?php
• $dbhost = 'localhost';
• $dbuser = 'root';
• $dbpass = '';
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass,"IT");
• if(! $conn )
• {
• die('Could not connect: ' . mysqli_error());
• }
• echo 'Connected successfully'."<br>";
• //mysqli_close($conn);
Create Table Cont..
• // sql to create table
• $sqli = "CREATE TABLE Thirdyear (
• Name VARCHAR(50) ,Code INT (20) )";
• if (mysqli_query($conn, $sqli)) {
• echo "Table Thirdyear created successfully";
• } else {
• echo "Error creating table: " . mysqli_error($conn);
•}
• mysqli_close($conn);
• ?> // Outputs
Created DB list
Created Table
Drop Table
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,"IT");
if(! $conn)
{
die('Could not connect: ' . mysqli_error());
}
echo "Connected successfully"."<br>" ;
Drop Table..
$sqli = "DROP TABLE IP";
$retval = mysqli_query( $conn,$sqli );
if(! $retval )
{
die('Could not delete table: ' . mysqli_error($conn));
}
echo "Table deleted successfully";
mysqli_close($conn);
?>
Send/Insert Data to a Database

• To insert data into MySQL table you would need to use SQL INSERT INTO
command
• Syntax:
• INSERT INTO table_name ( field1, field2,...fieldN ) VALUES ( value1, value2,...valueN ); or

• INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,...)

• When inserting data it is important to remember the exact names and types of the
table's columns.

• Requirements : form, database connection and the file name which is saved by
the action value (5-ddbb) .
Dbform,php
Database Connection
• <?php
• $host="localhost";
• $user="root";
• $pas="";
• $conn=mysqli_connect($host,$user,$pas,"it");
• if (!$conn)
• {
• die("Could not connect");
•}
• else {
• echo "Database Successfully Connected"."<br>";
•}
5-DDBB.php
• if (isset($_POST["register"])) {
• $Name=$_POST["name"];
• $Code=$_POST["code"];
• $sqli="INSERT INTO thirdyear (Name,Code)values('$Name','$Code')";
• if (mysqli_query($conn,$sqli)) {
• echo "new record inserted successfuly";
• }
• else
• echo "Error".mysqli_error($conn);
• }
• mysqli_close($conn)
• ?>
Retrieve Data from a Database

• In MySQL, data is retrieved with the "SELECT" keyword.

• The SELECT statement is used to select data from a database or we can


use the * character to select ALL columns from a table:
• SELECT * FROM table_name

• Before attempting to retrieve data, be sure that you have created a table
that contains some data.

• Syntax: SELECT column_name(s) FROM table_name


Cont..
• <?php
• $dbhost = 'localhost';
• $dbuser = 'root';
• $dbpass = '';
• $conn = mysqli_connect($dbhost, $dbuser, $dbpass,"IT");
• if(! $conn )
• {
• die('Could not connect: ' . mysqli_error());
• }
• $sqli = "SELECT name, code FROM thirdyear";
• $result = $conn->query($sqli);
Cont..
• if ($result->num_rows > 0) {
• echo "<table border=1> <tr> <th> NAME </th> <th> CODE</th>
</tr>";
• while ( $row=$result->fetch_assoc()) {
• echo "<tr> <td>".$row["name"]."</td>"."<td>".
$row["code"]."</td> </tr>" ;
• }
• echo "</table>";
• } else {
• echo "0 results";
•}
• $conn->close();
• ?>
Select and Filter Data From a MySQL Database

• The WHERE clause is used to filter records.

• The WHERE clause is used to extract only those records that fulfill a specified
condition.

• SELECT column_name(s) FROM table_name WHERE column_name operator


value

• $sqli = "SELECT Name, code FROM thirdyear WHERE Code=555";


Select and Filter Data From a MySQL Database
Modify/Updating Existing Data
• The UPDATE statement is used to update existing records in a table.

• UPDATE table_name SET column1=value, column2=value2,... WHERE


some_column=some_value

• Let's look at the “thirdyear" table before UPDATE:


• $sqli = "UPDATE thirdyear SET Code=999 WHERE Code=555";
Update Existing Data …
<?php
$host="localhost";
$user="root";
$pas="";
$conn=mysqli_connect($host,$user,$pas,"it");
if(!$conn)
{
die("could not connected".mysqli_error($conn));
}
$sqli = "UPDATE thirdyear SET Code=999 WHERE Code=555";
if ($conn->query($sqli) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>
Remove Existing Data
• The DELETE query is very similar to the UPDATE Query.

• We need to choose a table, tell MySQL to perform the deletion, and provide the

requirements that a record must have for it to be deleted.

• Syntax:DELETE from table_name where column_name comparison_operator

value

• Let's look at the “thirdyear" table before DELET:

$sqli = "delete from exam WHERE code=3030";


Remove Existing Data …
• <?php
• $host="localhost";
• $user="root";
• $pas="";
• $conn=mysqli_connect($host,$user,$pas,"it");
• if(!$conn)
• {
• die("could not connected".mysqli_error($conn));
• }
• $sqli = "delete from thirdyear WHERE code=3030";
• if ($conn->query($sqli) === TRUE) {
• echo "Record Delete successfully";
• } else {
• echo "Error Delete record: " . $conn->error;
• }

• $conn->close();
Data base security using server side scripting

• Nowadays, databases are fundamental components of any web based


application by enabling websites to provide varying dynamic content.

• Since very sensitive or secret information can be stored in a database, you


should strongly consider protecting your databases.

• To retrieve or to store any information you need to connect to the


database, send a legitimate query, fetch the result, and close the
connection.
Encryption in PHP

• Once an attacker gains access to your database directly (bypassing the web
server), stored sensitive data may be exposed or misused, unless the
information is protected by the database itself.

• Encrypting the data is a good way to mitigate this threat, but very few
databases offer this type of data encryption.

• The easiest way to work around this problem is to first create your own
encryption package, and then use it from within your PHP scripts.

• PHP provides different types of encryptions such as: md5, sha1, hash, crypt,
hashed_password etc.
Cont..
Example:
<?php
$pass="12345678";
echo "md5 encryption $pass=".md5($pass)."<br>";
echo "sha1 encryption $pass=".sha1($pass)."<br>";
echo "hash encryption $pass=".hash('sha1',$pass)."<br>";
echo "crypt encryption $pass=".crypt($pass,$salt);
?>
Output:
md5 encryption 12345678=25d55ad283aa400af464c76d713c07ad
sha1 encryption 12345678=7c222fb2927d828af22f592134e8932480637c0d
hash encryption 12345678=7c222fb2927d828af22f592134e8932480637c0d
crypt encryption 12345678=$1$.90.tj5.$CG0sUopGFc1ADWxBqDjPu.
In the above example, the salt parameter is optional. However, crypt () creates a weak password
without the salt. Make sure to specify a strong enough salt for better security.
Thank You!!!

You might also like