3 Chapter Edit
3 Chapter Edit
• One of the reasons for PHP’s popularity as a Web scripting language is its
(cross-platform, compatible, scalability, Allows for various DBs …. etc)
• Makes it easy for Web developers to create Web applications quickly and
efficiently.
Database Access in PHP
• Foreign Key: A foreign key is the linking pin between two tables.
• Referential Integrity: Referential Integrity makes sure that a foreign key value
always points to an existing row.
• Host name: This is the name of the server. We can change to whatever host
is acting as MySQL server. It is optional (localhost).
• 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().
mysqli_close($conn); or mysql_close($conn);
• 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.
• mysqli_query(connection variable,sql);
• 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.
• 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:
• 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
• 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
• Before attempting to retrieve data, be sure that you have created a table
that contains some data.
• The WHERE clause is used to extract only those records that fulfill a specified
condition.
$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
value
• $conn->close();
Data base security using server side scripting
• 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!!!