0% found this document useful (0 votes)
15 views

Chapter 3 & 4

Uploaded by

btekulu2020
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)
15 views

Chapter 3 & 4

Uploaded by

btekulu2020
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/ 27

Chapter Three

PHP MySQL Database

Introduction to MySQL
PHP is a language that gives you the flexibility to connect and work with
different databases while developing your web-page. There are different
databases, both commercial and free to use. Among them, MySQL is the most
commonly used database alongside PHP.

MySQL is an open-source, free-to-use relational database management


system (RDBMS). It is a fast, simple, and highly scalable program and hence
can be used for small as well as huge businesses.
What is MySQL?
MySQL is an open-source relational database management system (RDBMS).
It is the most popular database system used with PHP. MySQL is developed,
distributed, and supported by Oracle Corporation. The data in a MySQL
database are stored in tables which consists of columns and rows.
• 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 database system.
• It uses standard SQL
The data in a MySQL database are stored in tables. A table is a collection of
Connecting to databases
To connect PHP with database, four
important things must be taken place. Those
are:-
1. Define constants
2. Create connection using mysql_connect.
3. Select database.
4. Close connection.
1. Define constants
To connect php with database, defining
constants is very important. Constants that
must be defined are:-
 Define the server.
Define user name of the server.
Define password of the user.
Define database name.
 To define the constant, we can use as follows:
<?php
define("db_server","localhost");// the server that we use
define("db_user","root");// the username of the server
define("db_pass","");//password of the server
define("db_name","schoolmgt");//the database that we use
?>
2. Opening Database Connection
• After defining constants using php, opening or creating connection is
very important. To open or create database connection, we use
mysql_connect function.
• This function takes three parameters. Those are:
• db_server,db_user,db_pass.
The password of the user accessing the database.

The host name running database server The username accessing the database
From the above the host name running database server is “localhost”, the username accessing
the database is “user”, and the password of the user accessing the database is empty.
Connection can opened or created as follows:
$connection=mysql_connect(db_server,db_user,db_pass);
Example
<?php
$db_server = "localhost";
$db_user = "root";
$db_pass ="";
$db_name = "ip2";
$conn = "";
$conn = mysqli_connect($db_server,
$db_user,
$db_pass,
$db_name);
if($conn){
echo "you are connected!";
}
else{
echo "you are not connected";
}
?>
3. Select database
• Once you establish a connection with a database server then it is
required to select a particular database where your all the tables
are associated.
• This is required because there may be multiple databases
residing on a single server and you can do work with a single
database at a time.
• To select database, we use mysql_select_db as follows:-
$db_select=mysql_select_db(db_name,$connection);
4. Closing database connection
Its simplest function mysql_close PHP provides to close a database
connection. This function takes connection resource returned by
mysql_connect function. For example, to close the connection that you use
in the above; you use mysql_close function as follows:-
mysql_close($connection);
Create MySQL Database Using PHP
• To create and delete a database you should have admin privilege.
Its very easy to create a new MySQL database. PHP uses
mysql_query function to create a MySQL database. For example
to create the database test_db using php, you can write as follows:-
<?php
include("connect.php");
$sql = "CREATE DATABASE one";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn-
>error;
}
$conn->close();
?>
Creating Database Tables
• To create tables in the new database you need to do the
same thing as creating the database. First create the SQL
query to create the tables then execute the query using
mysql_query() function.
Cont…
• <?php
• include("connect.php");

• // sql to create table
• $sql = "CREATE TABLE MyGuests (
• id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
• firstname VARCHAR(30) NOT NULL,
• lastname VARCHAR(30) NOT NULL,
• email VARCHAR(50),
• reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
• )";

• if ($conn->query($sql) === TRUE) {
• echo "Table MyGuests created successfully";
• } else {
• echo "Error creating table: " . $conn->error;
• }

• $conn->close();
• ?>
Cont…
• In case you need to create many tables then its better to create a text
file first and put all the SQL commands in that text file and then
load that file into $sql variable and execute those commands.
Consider the following content in sql_query.txt file.
CREATE TABLE employee
(emp_id INT NOT NULL AUTO_INCREMENT,
emp_name VARCHAR(20) NOT NULL,
emp_address VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,
join_date timestamp(14) NOT NULL,
primary key ( emp_id ));
Insert Data into MySQL Database
Data can be entered into MySQL tables by executing SQL
INSERT statement through PHP function mysql_query.
Below a simple example to insert a record into employee
table.
sql = 'INSERT INTO employee '.
'(emp_name,emp_address, emp_salary, join_date) '.
'VALUES ( "guest", "XYZ", 2000, NOW() )';
Insert Data into MySQL Database
<?php
include("connect.php");

$sql = "INSERT INTO student (FullName, Department, Age,


Address)
VALUES ('Birhane Teklu', 'Information Science', '50',
'Shire')";

mysqli_query($conn, $sql);
mysqli_close($conn);

?>
Getting Data From MySQL Database
• Data can be fetched from MySQL tables by executing SQL
SELECT statement through PHP function mysql_query.
You have several options to fetch data from MySQL.
• The most frequently used option is to use function
mysql_fetch_array(). This function returns row as an
associative array, a numeric array, or both. This function
returns FALSE if there are no more rows.
• next is a simple example to fetch records from employee
table.
Cont…
$sql = 'SELECT emp_id, emp_name, emp_salary FROM
employee';
$retval = mysql_query($sql,$con);
if(!$retval ) {
die('Could not create table: ' . mysql_error());
}
while($row = mysql_fetch_array($retval,
MYSQL_ASSOC)) {
echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"EMP SALARY : {$row['emp_salary']} <br> ".
"--------------------------------<br>";
}
Cont…
• The content of the rows are assigned to the variable $row
and the values in row are then printed.
• 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 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.
Using mysql_fetch_assoc()
while($row = mysql_fetch_assoc($retval)) {
echo "EMP ID :{$row['emp_id']} <br> ".
"EMP NAME : {$row['emp_name']} <br> ".
"EMP SALARY : {$row['emp_salary']} <br> ".
"--------------------------------<br>";
}
Using MYSQL_NUM
while($row = mysql_fetch_array($retval, MYSQL_NUM)) {
echo "EMP ID :{$row[0]} <br> ".
"EMP NAME : {$row[1]} <br> ".
"EMP SALARY : {$row[2]} <br> ".
"--------------------------------<br>";
}
Example
<?php
include("connect.php");

$sql = "INSERT INTO student (FullName, Department, Age, Address)


VALUES ('Birhane Teklu', 'Information Science', '50',
'Shire’)”;

mysqli_query($conn, $sql);

mysqli_close($conn);

?>
Deleting Data from MySQL Database
• Data can be deleted from MySQL tables by executing SQL
DELETE statement through PHP function mysql_query.
• Below is a simple example to delete records into employee
table. To delete a record in any table it is required to locate
that record by using a conditional clause. Below example
uses primary key to match a record in employee table.
$emp_id = $_POST['emp_id'];
$sql = "DELETE FROM employee WHERE emp_id=
$emp_id" ;
Deleting MySQL Database and table Using PHP
• If a database is no longer required then it can be deleted forever. You
can use pass an SQL command to mysql_query to delete a database.
$sql = 'DROP DATABASE test_db’;

deleting MySQL database

$sql = 'DROP TABLE employee’;

deleting table
Example Deleting MySQL table Using PHP
<?php
include("connect.php");
$sql = "DELETE FROM student WHERE
ID=2";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
}
else {
echo "Error deleting record: " . $conn->error;

}
$conn->close();
Updating Data into MySQL Database
• Data can be updated into MySQL tables by executing SQL UPDATE
statement through PHP function mysql_query.
• Below is a simple example to update records into employee table. To
update a record in any table it is required to locate that record by
using a conditional clause. Below example uses primary key to match
a record in employee table.
$emp_id=$_POST['emp_id’];
$emp_salary = $_POST['emp_salary’];
$sql = "UPDATE employee ". "SET emp_salary = $emp_salary ". "WHERE
emp_id = $emp_id" ;
Updating Data into MySQL Database
<?php
include("connect.php");

$sql = "UPDATE student SET FullName='Hagos' WHERE


ID=3";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
}
else {

echo "Error updating record: " . $conn-


>error;
}
$conn->close();

?>
Chapter Four
PHP Cookies

• A cookie is often used to identify a user.

What is a Cookie?
• A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each
time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and
retrieve cookie values.

Create Cookies With PHP


• A cookie is created with the setcookie() function.
Syntax
• setcookie(name, value, expire, path, domain, secure, httponly);
• Only the name parameter is required. All other parameters are optional.
PHP Create/Retrieve a Cookie
• The following example creates a cookie named "user" with the value "John Doe". The cookie will expire after 30 days
(86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you prefer).
• We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the isset() function
to find out if the cookie is set:
Note: The setcookie() function must appear BEFORE the <html> tag.
Cont…
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
PHP Sessions

• A session is a way to store information (in variables) to be used across multiple pages.
• Unlike a cookie, the information is not stored on the users computer.
• Session variables hold information about one single user, and are available to all pages in one application.
• If you need a permanent storage, you may want to store the data in a database.
• A session is started with the session_start() function.
• Session variables are set with the PHP global variable: $_SESSION.
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Cont…
• Note: The session_start() function must be the very first thing in your document. Before any HTML tags.
Get PHP Session Variable Values
• Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Destroy a PHP Session
• To remove all global session variables and destroy the session, use session_unset() and session_destroy():
Cont…
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

You might also like