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

Unit 5 Working With Database in PHP 5.1 to 5.4

This document provides an overview of working with MySQL databases using PHP, including creating databases and tables, executing queries, and performing various database operations. It introduces key concepts such as Database Management Systems (DBMS), phpMyAdmin, and MySQLi, along with practical steps for database management through both phpMyAdmin and console commands. Additionally, it covers data types in MySQL and methods for connecting and interacting with databases using PHP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit 5 Working With Database in PHP 5.1 to 5.4

This document provides an overview of working with MySQL databases using PHP, including creating databases and tables, executing queries, and performing various database operations. It introduces key concepts such as Database Management Systems (DBMS), phpMyAdmin, and MySQLi, along with practical steps for database management through both phpMyAdmin and console commands. Additionally, it covers data types in MySQL and methods for connecting and interacting with databases using PHP.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Unit 5

WORKING WITH DATABASE IN PHP


5.1. Introduction to MySQL Database with PHP
5.2. Creating a database using phpMyAdmin & console
5.3. Connecting with MySQL database
5.4. Executing MySQL queries
5.5. Performing database operations
i. Create/delete a table
ii. Insert data into the table
iii. Update data into the table
iv. Retrieve data from the table
v. Delete data from the table
5.6. Displaying data from the database in different formats, including tables
5.7. Working on mini-project: Developing simple web application and hosting it on
web server

R.C.T.I computer 2
Database:
Database is a collection of inter-related data which helps in efficient retrieval, insertion and
deletion of data from database and organizes the data in the form of tables, views, schemas,
reports etc. For Example, university database organizes the data about students, faculty, and
admin staff etc. which helps in efficient retrieval, insertion and deletion of data from it.
DBMS:
A database management system (DBMS) is system software for creating and managing
database.
RDBMS:
RDBMS stands for Relational Database Management System.
RDBMS is a program used to maintain a relational database.
RDBMS is the basis for all modern database systems such as MySQL, Microsoft SQL
Server, Oracle, and Microsoft Access.
RDBMS uses SQL queries to access the data in the database
R.C.T.I computer 3
phpMyAdmin
phpMyAdmin is an open-source software tool which is written in PHP.

phpMyAdmin supports various type of operations on MariaDB and MySQL.

The main purpose of phpMyAdmin is to handle the administration of MySQL over the web.

We can create, update, drop, alter, delete, import, and export MySQL database tables by
using this software.

phpMyAdmin also supports a wide range of operation like managing databases, relations,
tables, columns, indexes, permissions, and users, etc., on MySQL.

phpMyAdmin is a GUI-based application which is used to manage MySQL database.

R.C.T.I computer 4
5.1. Introduction to MySQL Database with PHP

MySQL database
MySQL is the most popular database system used with PHP.
MySQL:-
• MySQL is a database system used on the web
• 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
• MySQL uses standard SQL
• MySQL compiles on a number of platforms
• MySQL is free to download and use
• MySQL is developed, distributed, and supported by Oracle Corporation
• MySQL is named after co-founder Monty Widenius's daughter: My
PHP combined with MySQL are cross-platform (you can develop in Windows and serve on
a Unix platform)

R.C.T.I computer 5
5.2. Creating a database using phpMyAdmin & console
5.2.1 Creating a database using phpMyAdmin
Step 1: Open a web browser, enter a URL http://localhost to access XAMPP
dashboard. Select phpMyAdmin tab

R.C.T.I computer 6
• The main page should look similar to the following

R.C.T.I computer 7
• Add a user account
1. On the phpMyAdmin screen, select User accounts tab.
2. Select Add user account link.
3. Enter user name and password of your choice.
4. Select Local for Host name.
5. Check Create database with same name and grant all privileges.
6. Check Grant all privileges on wildcard name (username\_%).
7. Check Check all for Global privileges
8. At the bottom-right of the screen, click the Go button.

https://www.cs.virginia.edu/~up3f/cs4640/supplement/DB-setup-xampp.html
R.C.T.I computer 8
R.C.T.Iaccount
To verify that the account has been created, go to User computer tab. You should see the newly created user account
9 .
R.C.T.I computer 10
R.C.T.I computer 11
Step 2: Select Database menu item: Click on Database Menu where we marked.

Under the Create database, enter a Database name. Click the Create button.
R.C.T.I computer 12
You may run the SQL command to create a database.
• On the phpMyAdmin screen, select the SQL tab.
• Enter CREATE DATABASE guestbook;
Note: SQL commands are not case sensitive. This example uses uppercase and lowercase simply to
make it easy to read.
• Click the Go button to run the command.

R.C.T.I computer 13
Step 3: Database ending: Your database is created. You can find that one on
leftside.

R.C.T.I computer 14
5.2.2 Creating Database using Console
Click on Shell to start cmd.

R.C.T.I computer 15
Use mysql command “mysql –uroot –p” to login into mysql, here –u for taking user name of mysql and –p
for password.
phpMyAdmin default user name is:root and password :null/nothing(blank)
Note: just hit enter without entering anything.
To create a database with the name prisha type the following command: create database prisha;
R.C.T.I computer 16
• Create table
On the phpMyAdmin screen, select the guestbook database.
Select the Structure tab.
Under the Create table, enter a table name and the number of columns.
Click the Go button. This will prompt you to enter the column information.

R.C.T.I computer 17
You may run the SQL command to create a table.
On the phpMyAdmin screen,select the SQL tab ,enter the following code.
Use guestbook;
CREATE TABLE entries (guestName VARCHAR(255), content VARCHAR(255),
entryID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(entryID));

R.C.T.I computer 18
Insert Data
On the phpMyAdmin screen,
select the guestbook database,
select the entries table.
Select the Insert tab.
For each record of data to be
inserted, enter the value for each
column.
Click the Go button

R.C.T.I computer 19
You may run the SQL
command to insert data.
On the phpMyAdmin screen,
select the guestbook database,
select the entries table.
Select the SQL tab
Enter the following code

INSERT INTO entries (guestName, content) values ("Humpty", "Humpty's here!");


INSERT INTO entries (guestName, content) values ("Dumpty", "Dumpty's here too!");

R.C.T.I computer 20
You may run the SQL
command to retrieve data.
On the phpMyAdmin screen,
select the guestbook database,
select the entries table.
Select the SQL tab
Enter the following code:
SELECT * FROM entries;

R.C.T.I computer 21
Data types (field types) of MySQL

• MySQL uses many different data types broken into three categories:
o Numeric
o Date and Time
o String Types

R.C.T.I computer 22
Numeric

TINYINT 1-byte integer Signed range is from -128 to 127


Unsigned range is from 0 to 255
SMALLINT 2-byte integer Signed range is from -32768 to 32767
Unsigned range is from 0 to 65535
MEDIUMINT 3-byte integer Signed range is from -8388608 to 8388607
Unsigned range is from 0 to 16777215
INT 4-byte integer Signed range is from -2147483648 to 2147483647
Unsigned range is from 0 to 4294967295
BIGINT 8-byte integer Signed range is from -9223372036854775808 to
9223372036854775807
Unsigned range is from 0 to 18446744073709551615

R.C.T.I computer 23
Numeric
FLOAT(size,d) Single-precision Size- total number of digits
d-number of digits after the decimal
point.
Decimal precision can go to 24
places for a float type. It requires 2
bytes for storage.
DOUBLE(size,d) Double-precision Size- total number of digits
d-number of digits after the decimal
point.
Decimal precision can go to 53
places for a double. Real is a
synonym for double. It requires 8
bytes for storage.
DECIMAL(size, d) Fixed-point decimal number Size- total number of digits
d-number of digits after the decimal
point.
The maximum number for size is 65.
The maximum number for d is 30.

R.C.T.I computer 24
Date and Time Data Types

DATE Values range from '1000-01-01' Displayed as 'yyyy-mm-dd'. It


to '9999-12-31'. takes 3 bytes for storage.
TIME Values range from '-838:59:59' to Displayed as 'HH:MM:SS'. It
'838:59:59'. takes 3 bytes plus fractional
seconds for storage.
DATETIME Values range from '1000-01-01 Displayed as 'yyyy-mm-dd
00:00:00' to '9999-12-31 hh:mm:ss'. It takes 5 bytes plus
23:59:59'. fractional seconds for storage.
TIMESTAMP Values range from '1970-01-01 Values range from '1970-01-01
00:00:01' UTC to '2038-01-19 00:00:01' UTC to '2038-01-19
03:14:07' TC. 03:14:07' TC.
YEAR Year value as 2 digits or 4 digits. The default is 4 digits. It takes 1
byte for storage.

UTC (Coordinated Universal Time)


R.C.T.I computer 25
R.C.T.I computer 26
• Other datatypes

R.C.T.I computer 27
MySQLi is also known as MySQL improved Extension. It is a relational
SQL database management system. It is often used inside PHP to
provide an interface with the MySQL databases.

R.C.T.I computer 28
PHP 5 and later can work with a MySQL database using:
• MySQLi extension (the "i" stands for improved)

Two approach working with PHP and MySQL:


• MySQLi (object-oriented) This method uses objects and
methods to interact with the database.
• MySQLi (procedural) This method uses functions instead of
objects.

R.C.T.I computer 29
• Integration of PHP with MYSQL
 mysql_connect — Open a connection to a MySQL Server
mysql_select_db — Select a MySQL database
mysql_query — Send a MySQL query
mysql_fetch_row — Get a result row as an enumerated array
mysql_fetch_array — Fetch a result row as an associative array, a numeric
array, or both
mysql_error — Returns the text of the error message from previous MySQL
operation
mysql_close — Close MySQL connection
mysql_create_db — Create a MySQL database
mysql_fetch_assoc — Fetch a result row as an associative array

R.C.T.I computer 30
5.3 Connecting with MYSQL database
 mysqli_connect() function opens a new connection to the MySQL server.
Syntax: mysqli_connect(host, username, password, dbname, port, socket)

 mysqli_close() function closes a previously opened database connection.


Syntax: mysqli_close(connection)
R.C.T.I computer 31
 mysqli_connect_error()
• PHP mysqli_connect_error() function returns the error description from the
last connection error, if any. If the connection was successful this function
returns Null.
• Syntax:
mysqli_connect_error()

 mysqli_error() function returns the last error description for the most recent
function call, if any. If there are no errors this function returns an empty
string.
• Syntax:
mysqli_error(connection)

 die() function is an alias of the exit() function.

R.C.T.I computer 32
Open a Connection to MySQL (Procedural style)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname= "prisha";

// Connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check if connection is Successful or not


O/P: Connection failed: Access
if (!$conn)
denied for user
{ ‘root'@'localhost' (using
die("Connection failed: ". mysqli_connect_error()); password: YES)
}
echo "Connected successfully";
mysqli_close($conn); O/P: Connected successfully
?> R.C.T.I computer 33
Using mysqli_error() (Procedural style) // Example of an incorrect SQL query
<?php $sql = "SELECT * FORM users";
$servername = "localhost"; // Error: "FROM" is misspelled as
$username = "root"; "FORM"
$password = "";
$dbname = "testdb"; $result = mysqli_query($conn, $sql);

// Create connection
if (!$result)
$conn = mysqli_connect($servername, $username,
$password, $dbname); {
echo "Error executing query: " .
// Check connection mysqli_error($conn);
if (!$conn) }
{ mysqli_close($conn);
die("Connection failed: " . mysqli_connect_error()); ?>
} Error executing query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right
syntax to use near 'FORM users' at line 1 34
5.4 Executing MySQL queries
 mysqli_query() function performs a query against a database.
Syntax:
mysqli_query(connection, query, resultmode)

R.C.T.I computer 35
 mysqli_num_rows() function returns the number of rows in a result
set.
Syntax: mysqli_num_rows(result);
result: Required. Specifies a result set identifier retured by
mysqli_query().

 mysqli_fetch_assoc() function fetches a result row as an associative


array.
Syntax: mysqli_fetch_assoc(result)
result- Required. Specifies a result set identifier returned by
mysqli_query().

R.C.T.I computer 36
CODE:
$sql = "SELECT * FROM student";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
O/P:
{ // output data of each row Rollno Name Result
echo "<b>Rollno Name Result</b> <br/>"; 1 Diva A
while($row = mysqli_fetch_assoc($result)) 2 Liva A

{ $a=$row["sno"];
$b=$row["sname"];
$c=$row["result"];
echo $a ."&nbsp ";
echo $b ."&nbsp ";
echo $c. '<br/>';
}
} else {
echo "0 results";
} mysqli_close($conn);
R.C.T.I computer 37

You might also like