Chapter : Three
Connecting to Databases
• 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.
• Primary Key: is unique a key value can not occur twice in one table.
Cont.…
• Foreign Key: a key originated from another table. It is the primary key in another
table. It define a relationship with another table.
• Compound Key: (composite key) is a key which has multiple attributes to uniquely
identify rows in a table.
• Super key :is a set of attributes within a table that can identify uniquely identify each
row within a table. It counties any no’ attributes from table attributes to make super
key.
• Candidate key: is a minimal set of super keys. It takes a common attributes from
both super key. It is a subset of super key.
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($a) 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.
• User name: The root user of the system.
• User’s password:-This is encrypted written with the form for security.
Creating a Database Connection
• 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_linkOptional – is a Boolean parameter that determines whether to open a new connection
to the MySQL server or to reuse an exiting one. If new_link is set “true”, it will attempt to
open a new connection. If set to “false (default), it will reuse an exiting connection if
available.
 client_flags Optional - allow you to specify various options and behaviors for
connection. It is 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.
Database connection
• If data base (DB) name exists as a parameter, the value of $user should “root”, unless it will
generate the following error messages.
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:
 mysqli_close ( $link_identifier );
 mysqli_close($a);
This function returns true if it closes connection successfully otherwise it returns
false.
Closing a DB connection
•<?php
•$host=“ “ // can you change the order of variable with their value?
•$user=‘ root'; // single quote and double quote treated as the same.
•$pas=‘ ‘;
•$a= mysqli_connect($host, $user, $pas);//when we can change the order of
parameters ?
• if(! $a )
• {
• die('Could not connect: ' . mysqli_error());
• }
• echo 'Connected successfully';
•mysqli_close($a); // Don’t use this function in DB connection.
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() 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.
Creating the working Database
• The syntax of the function is:-
• mysqli_query(connection variable,sqli);
• To create a database uses the following sql syntax:
• CREATE DATABASE database_name
• mysqli_query ($connection,"create database Mid”): told MySQL to create a
database called mid.
• $sqli=mysqli_query($a,"create database Mid");
Creating the working Database…
• 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…
Creating the working Database..
• There are also functions in PHP which have different purposes. For instance,
• 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.
Creating the working Database
• 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
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 TABLEtable_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
• $host = 'localhost';
• $user = "root";
• $pas = "";
• $a= mysqli_connect($host,$user,$pas,"final");
• if(! $a ){
• die('Could not connect: ' . mysqli_error()); }
• echo 'Connected successfully'. "<br>";
• $sqli="CREATE TABLE html (UserName VARCHAR(50) Not
NULL,Password VARCHAR(30) NOT NULL)";
• if (mysqli_query($a, $sqli)) {
• echo "Table created successfully";
•} else {
• echo "Error creating table: " . mysqli_error($a);}
•mysqli_close($a);
•?>
Drop Table
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 (8-ddbb) .
Dbform,php
Database Connection and 8-DDBB
Form and Database
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
Retrieve Data from a Database…
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 UseName, Password FROM IP WHERE password=33";
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 “IP" table before UPDATE:
• $sqli = "UPDATE IP SET password=444 WHERE Code=33";
Update Existing Data …
<?php
$host="localhost";
$user="root";
$pas="";
$a=mysqli_connect($host,$user,$pas,"mid");
if(!$a){
die("could not connected".mysqli_error($a));}
$sqli = "UPDATE IP SET password=444 WHERE password=33";
if ($a->query($sqli) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $a->error;}
$a->close();
?>
Delete an 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 “IP" table before DELET:
$sqli = "delete from IP WHERE Password=1234";
Delete an Existing Data…
• <?php
• $dbhost = 'localhost';
• $dbuser = 'root';
• $dbpass = '';
• $a= mysqli_connect($dbhost, $dbuser, $dbpass,"mid");
• if(! $a) {
• die('Could not connect: ' . mysqli_error()); }
• $sqli = "DELETE FROM IP WHERE password=1234";
• if ($a->query($sqli) === TRUE) {
• echo "Record deleted successfully";
• } else {
• echo "Error deleting record: " . $a->error;}
• $a->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="123";
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:
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!!!

3-Chapter-Edit.pptx debre tabour university

  • 1.
    Chapter : Three Connectingto Databases • 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.
  • 2.
    Database Access inPHP • 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. • Primary Key: is unique a key value can not occur twice in one table.
  • 3.
    Cont.… • Foreign Key:a key originated from another table. It is the primary key in another table. It define a relationship with another table. • Compound Key: (composite key) is a key which has multiple attributes to uniquely identify rows in a table. • Super key :is a set of attributes within a table that can identify uniquely identify each row within a table. It counties any no’ attributes from table attributes to make super key. • Candidate key: is a minimal set of super keys. It takes a common attributes from both super key. It is a subset of super key.
  • 4.
    MySQL Database • MySQLis 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).
  • 5.
    Database Interactions PHP databaseinteractions in five steps: Create a database connection Perform Database query Use returned data if any Release returned data Close database connection
  • 6.
    Creating a DatabaseConnection • Before we enable do anything with database in PHP, we should first connect to the MySQL server using specific connection variables. • Connection variables($a) 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. • User name: The root user of the system. • User’s password:-This is encrypted written with the form for security.
  • 7.
    Creating a DatabaseConnection • 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.
  • 8.
    Cont.… • new_linkOptional –is a Boolean parameter that determines whether to open a new connection to the MySQL server or to reuse an exiting one. If new_link is set “true”, it will attempt to open a new connection. If set to “false (default), it will reuse an exiting connection if available.  client_flags Optional - allow you to specify various options and behaviors for connection. It is 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.
  • 9.
    Database connection • Ifdata base (DB) name exists as a parameter, the value of $user should “root”, unless it will generate the following error messages.
  • 10.
    Closing a DBconnection • 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:  mysqli_close ( $link_identifier );  mysqli_close($a); This function returns true if it closes connection successfully otherwise it returns false.
  • 11.
    Closing a DBconnection •<?php •$host=“ “ // can you change the order of variable with their value? •$user=‘ root'; // single quote and double quote treated as the same. •$pas=‘ ‘; •$a= mysqli_connect($host, $user, $pas);//when we can change the order of parameters ? • if(! $a ) • { • die('Could not connect: ' . mysqli_error()); • } • echo 'Connected successfully'; •mysqli_close($a); // Don’t use this function in DB connection.
  • 12.
    Creating the workingDatabase • 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() 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.
  • 13.
    Creating the workingDatabase • The syntax of the function is:- • mysqli_query(connection variable,sqli); • To create a database uses the following sql syntax: • CREATE DATABASE database_name • mysqli_query ($connection,"create database Mid”): told MySQL to create a database called mid. • $sqli=mysqli_query($a,"create database Mid");
  • 14.
    Creating the workingDatabase… • 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
  • 15.
  • 16.
  • 17.
    Creating the workingDatabase.. • There are also functions in PHP which have different purposes. For instance, • 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.
  • 18.
    Creating the workingDatabase • 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.
  • 19.
  • 20.
    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 TABLEtable_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.
  • 21.
    Create Table Cont.. •<?php •$host = 'localhost'; • $user = "root"; • $pas = ""; • $a= mysqli_connect($host,$user,$pas,"final"); • if(! $a ){ • die('Could not connect: ' . mysqli_error()); } • echo 'Connected successfully'. "<br>"; • $sqli="CREATE TABLE html (UserName VARCHAR(50) Not NULL,Password VARCHAR(30) NOT NULL)"; • if (mysqli_query($a, $sqli)) { • echo "Table created successfully"; •} else { • echo "Error creating table: " . mysqli_error($a);} •mysqli_close($a); •?>
  • 22.
  • 23.
    Send/Insert Data toa 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 (8-ddbb) .
  • 24.
  • 25.
  • 26.
  • 27.
    Retrieve Data froma 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
  • 28.
    Retrieve Data froma Database…
  • 29.
    Select and FilterData 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 UseName, Password FROM IP WHERE password=33";
  • 30.
    Select and FilterData From a MySQL Database
  • 31.
    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 “IP" table before UPDATE: • $sqli = "UPDATE IP SET password=444 WHERE Code=33";
  • 32.
    Update Existing Data… <?php $host="localhost"; $user="root"; $pas=""; $a=mysqli_connect($host,$user,$pas,"mid"); if(!$a){ die("could not connected".mysqli_error($a));} $sqli = "UPDATE IP SET password=444 WHERE password=33"; if ($a->query($sqli) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $a->error;} $a->close(); ?>
  • 33.
    Delete an ExistingData • 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 “IP" table before DELET: $sqli = "delete from IP WHERE Password=1234";
  • 34.
    Delete an ExistingData… • <?php • $dbhost = 'localhost'; • $dbuser = 'root'; • $dbpass = ''; • $a= mysqli_connect($dbhost, $dbuser, $dbpass,"mid"); • if(! $a) { • die('Could not connect: ' . mysqli_error()); } • $sqli = "DELETE FROM IP WHERE password=1234"; • if ($a->query($sqli) === TRUE) { • echo "Record deleted successfully"; • } else { • echo "Error deleting record: " . $a->error;} • $a->close(); • ?>
  • 35.
    Data base securityusing 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.
  • 36.
    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.
  • 37.
    Cont.. Example: <?php $pass="123"; 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: 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.
  • 38.

Editor's Notes