Chapter 3 & 4
Chapter 3 & 4
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.
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");
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");
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 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");
?>
Chapter Four
PHP Cookies
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.
• 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>