0% found this document useful (0 votes)
5 views13 pages

Chapter5 - Database Handling Using PHP With MySQL

The document provides an overview of database handling using PHP with MySQL, covering topics such as MySQL introduction, data types, and connection methods. It details the features and advantages of MySQL and phpMyAdmin, along with their differences and functionalities for managing databases. Additionally, it explains various PHP MySQL functions for database connectivity and operations, including examples of connecting to a database and executing queries.

Uploaded by

chethana8182
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)
5 views13 pages

Chapter5 - Database Handling Using PHP With MySQL

The document provides an overview of database handling using PHP with MySQL, covering topics such as MySQL introduction, data types, and connection methods. It details the features and advantages of MySQL and phpMyAdmin, along with their differences and functionalities for managing databases. Additionally, it explains various PHP MySQL functions for database connectivity and operations, including examples of connecting to a database and executing queries.

Uploaded by

chethana8182
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/ 13

III BCA (NEP) PHP and MySQL SUMA N | Dept.

of CS

Chapter-5: Database Handling Using PHP with MySQL


Introduction to MySQL: Database terms, Data Types. Accessing MySQL –Using MySQL Client and
Using php MyAdmin, MySQL Commands, PHP MySQL Functions, Connecting to MySQL and Selecting
the Database, Executing Simple Queries, Retrieving Query Results, Counting Returned Records,
Updating Records with PHP.

DBMS
DBMS is a software or group of programs designed to perform database operations such as creating a new
database, administering and managing the databases by performing various user-specified database
operations. The DBMS internally might consist of a group of programs each performing different tasks related
to database management. Some DBMS examples, My SQL, Oracle, System 2000, MS Access, My SQL server, etc.

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 consist 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
• MySQL compiles on a number of platforms.

The features of MySQL are as follows:


• Ease of Management – The software very easily gets downloaded and also uses an event scheduler to
schedule the tasks automatically.
• Robust Transactional Support – Holds the ACID (Atomicity, Consistency, Isolation, and Durability)
property, and also allows distributed multi-version support.
• Comprehensive Application Development – MySQL has plugin libraries to embed the database into any
application. It also supports stored procedures, triggers, functions, views and many more for application
development.
• High Performance – Provides fast load utilities with distinct memory caches and table index partitioning.
• Low Total Cost Of Ownership – This reduces licensing costs and hardware expenditures.
• Open Source & 24 * 7 Support – This RDBMS can be used on any platform and offers 24*7 supports for
open source and enterprise edition.
• Secure Data Protection – MySQL supports powerful mechanisms to ensure that only authorized users
have access to the databases.
• High Availability – MySQL can run high-speed master/slave replication configurations and it offers cluster
servers.
• Scalability & Flexibility – With MySQL you can run deeply embedded applications and create data
warehouses holding a humongous amount of data.

MySQL Data Types

UCS, Tumkur Page 1


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

• Numeric – This data type includes integers of various sizes, floating-point(real) of various precisions and
formatted numbers.
• Character-string – These data types either have a fixed, or a varying number of characters. This data type
also has a variable-length string called CHARACTER LARGE OBJECT (CLOB) which is used to specify columns
that have large text values.
• Bit-string – These data types are either of a fixed length or varying length of bits. There is also a variable-
length bit string data type called BINARY LARGE OBJECT(BLOB), which is available to specify columns that
have large binary values, such as images.
• Boolean – This data type has TRUE or FALSE values. Since SQL, has NULL values, a three-valued logic is
used, which is UNKNOWN.
• Date & Time – The DATE data type has: YEAR, MONTH, and DAY in the form YYYY-MM-DD. Similarly, the
TIME data type has the components HOUR, MINUTE, and SECOND in the form HH:MM: SS. These formats
can change based on the requirement.
• Timestamp & Interval – The TIMESTAMP data type includes a minimum of six positions, for decimal
fractions of seconds and an optional WITH TIME ZONE qualifier in addition to the DATE and TIME fields.
The INTERVAL data type mentions a relative value that can be used to increment or decrement an absolute
value of a date, time, or timestamp.

Connecting to MySQL database using PHP


PHP 5 and later can work with a MySQL database using:
1. MySQLi extension.
2. PDO (PHP Data Objects).
Difference between MySQLi and PDO
• PDO works on 12 different database systems, whereas MySQLi works only with MySQL databases.
• Both PDO and MySQLi are object-oriented, but MySQLi also offers a procedural API.
• If at some point of development phase, the user or the development team wants to change the database
then it is easy to that in PDO than MySQLi as PDO supports 12 different database systems. He would have
to only change the connection string and a few queries. With MySQLi, he will need to rewrite the entire
code including the queries.

There are three ways of working with MySQl and PHP


1. MySQLi (object-oriented)
2. MySQLi (procedural)
3. PDO

Using MySQLi object-oriented procedure: We can use the MySQLi object-oriented procedure to establish a
connection to MySQL database from a PHP script.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = new mysqli($servername, $username, $password);
// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

UCS, Tumkur Page 2


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Using MySQLi procedural procedure : There is also a procedural approach of MySQLi to establish a
connection to MySQL database from a PHP script as described below.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Using PDO procedure: PDO stands for PHP Data Objects. That is, in this method we connect to the database
using data objects in PHP as described below:
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// setting the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

phpMyAdmin
phpMyAdmin is an open-source software tool introduced on September 9, 1998, which is written in PHP.
Basically, it is a third-party tool to manage the tables and data inside the database. 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.
It is the most popular application for MySQL database management. 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 and MariaDB. These operations can be performed via user interface, while we still have the ability to
execute any SQL statement.
phpMyAdmin is translated into 72 languages and also supports both RTL and LTR languages so that the wide
range of people can easily use this software. We can run MySQL queries, repair, optimized, check tables, and
also execute other database management commands. phpMyAdmin can also be used to perform administrative
tasks such as database creation, query execution.
phpMyAdmin is a GUI-based application which is used to manage MySQL database. We can manually create
database and table and execute the query on them. It provides a web-based interface and can run on any server.
Since it is web-based, so we can access it from any computer.

UCS, Tumkur Page 3


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Features of phpMyAdmin
phpMyAdmin supports several features that are given below:
o phpMyAdmin can create, alter, browse, and drop databases, views, tables, columns, and indexes.
o It can display multiple results sets through queries and stored procedures.
o phpMyAdmin use stored procedure and queries to display multiple results sets.
o It supports foreign keys and InnoDB tables.
o phpMyAdmin can track the changes done on databases, views, and tables.
o We can also create PDF graphics of our database layout.
o phpMyAdmin can be exported into various formats such as XML, CSV, PDF, ISO/IEC 26300 - Open
Document Text and Spreadsheet.
o It supports mysqli, which is the improved MySQL extension.
o phpMyAdmin can interact with 80 different languages.
o phpMyAdmin can edit, execute, and bookmark any SQL-statements and even batch-queries.
o By using a set of pre-defined functions, it can transform stored data into any format. For example - BLOB-
data as image or download-link.
o It provides the facility to backup the database into different forms.

Advantage of phpMyAdmin
o phpMyAdmin can run on any server or any OS as it has a web browser.
o We can easily create, delete, and edit the database and can manage all elements using the graphical
interface of phpMyAdmin, which is much easier than MySQL command-line editor.
o phpMyAdmin helps us to control the user's permission and operate several servers at the same time.
o We can also backup our database and export the data into different formats like XML, CSV, SQL, PDF,
OpenDocument Text, Excel, Word, and Spreadsheet, etc.
o We can execute complex SQL statements and queries, create and edit functions, triggers, and events using
the graphical interface of phpMyAdmin.

Disadvantage of phpMyAdmin
o phpMyAdmin is a simple interface, but quite tough for a beginner to learn.
o phpMyAdmin is difficult to install as it needs three more software tools before installation, which is-
Apache server, PHP, and MySQL.
o We have to install all these software tools individually, whereas XAMPP already contains them in a single
package. XAMPP is the easiest way to get phpMyAdmin.
o It has no schema visualization.
o phpMyAdmin is a web-based software tool which runs only on the browser, so It completely depends on
browsers.
o It does not have auto-compilation capability.

Data Backup problem with phpMyAdmin


phpMyAdmin lacks a lot of features in import/export functionality. There are some backup problems with
phpMyAdmin that are given below:
o Scheduling - There is no way to export the data of the database in phpMyAdmin automatically.
o Storage media support - As we have discussed earlier, phpMyAdmin is web-based software, so it runs
only on the browser. We can take backups only to local drives of our system.
o Compression, Encryption, and other option - The files which are exported with phpMyAdmin are saved
as common text files, with any additional processing. Whereas storing these files in the original form
usually takes a lot of disk storage.

Difference between phpMyAdmin and MySQL Console


1. phpMyAdmin provides a user interface through which we can execute query within SQL. We can also paste
the query into SQL to test our output, whereas on MySQL Console we cannot copy and paste queries. We
have to write query every time to execute on MySQL console.

UCS, Tumkur Page 4


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

2. MySQL is a database server, on the other hand, phpMyAdmin is a server tool to access the database on
MySQL server.
3. We have to learn database query to create, delete, alter, update, and drop to execute on MySQL console,
whereas in phpMyAdmin we can do it using graphical user interface which automatically executes these
queries in background.

Note: In simple words, MySQL is a database, and phpMyAdmin is a software tool to access data from that
database.

PHP_MySQL-DB functions
In PHP Scripting language many functions are available for MySQL Database connectivity and executing SQL
queries.
MySQLi is extension in PHP scripting language which gives access to the MYSQL database. MySQLi extension
was introduced version 5.0.0,
The MySQLi extension contains the following important functions which are related to MySQL database
connectivity and management.
● Mysqli_connect() Function
● Mysqli_close() Function

UCS, Tumkur Page 5


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

● Mysqli_query()Function

Database Connections:
Before accessing MySQL Database, connect to Database Server machine via PHP scripting language using
Mysqli_connect() Function.
Syntax:
mysqli_connect(“Server Name “,”User Name”,”Password”,”DB Name”);
This function requires four parameters to connect to database server. Database Server name, Database
username, password and Database Name.

Connecting to MySQL database using PHP (Using MySQLi procedural procedure):


The procedural approach of MySQLi to establish a connection to MySQL database from a PHP script as
described below.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Output:

Explanation: In MySQLi procedural approach instead of creating an instance we can use the
mysqli_connect() function available in PHP to establish a connection. This function takes the information as
arguments such as host, username, password, database name etc. This function returns MySQL link identifier
on successful connection or FALSE when failed to establish a connection.

Managing Database Connections


The below code describes managing database connection methods and features.
<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$DB_name = “School_DB”;
$conn = mysqli_connect($servername, $username, $password,$DB_name);
if (!$conn) {
die(“Connection failed: “ . mysqli_connect_error());
}
echo “Connected successfully”;
?>

In the above code snippet, four variables are used to connect to the Database server. They are
● $servername -> Database Server Server IP address
● $username -> Database Server User Name

UCS, Tumkur Page 6


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

● $password -> Database Server Password


● $DB_Name -> Database Name
The mysqli_connect function uses these variables to connect Database server to PHP. If connection gets fail,
output will be printed with MySQL error code. Otherwise connection is success.

Performing Queries
The main goal of MySQL and PHP connectivity is to retrieve and manipulate the data from MySQL database
server. The SQL query statements help in PHP MySQL extension to achieve the objective of MySQL and PHP
connection. “mysqli_query” is a function, that helps to execute the SQL query statements in PHP scripting
language.
Syntax:
mysqli_query(“Connection Object”,”SQL Query”)
Example:
$con=mysqli_connect(“localhost”,”my_user”,”my_password”,”Student_DB “);
$sql=”SELECT student_name,student_age FROM student”;mysqli_query($con,$sql);

Closing Connection:
mysqli_close() Function is used to close an existing opened database connection between PHP scripting and
MySQL Database Server.
Syntax:
mysqli_close(“Connection Object”);
Example:
<?php
$con=mysqli_connect(“localhost”,”$user”,”$password”,”SCHOOL_DB”);
mysqli_close($con);
?>

PHP mysqli_select_db function


The mysqli_select_db function is used to select a database.
It has the following syntax.
<?php
mysqli_select_db($db_handle,$database_name);
?>
HERE,
• “mysqli_select_db(…)” is the database selection function that returns either true or false
• “$database_name” is the name of the database
• “$link_identifier” is optional, it is used to pass in the server connection link

PHP mysqli_num_rows function


The mysqli_num_rows function is used to get the number of rows returned from a select query.
It has the following syntax.
<?php
mysqli_num_rows($result);
?>
HERE,
• “mysqli_num_rows(…)” is the row count function
• “$result” is the mysqli_query result set

PHP mysqli_fetch_array function


The mysqli_fetch_array function is used fetch row arrays from a query result set.
It has the following syntax.
<?php

UCS, Tumkur Page 7


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

mysqli_fetch_array($result);
?>
HERE,
• “mysqli_fetch_array(…)” is the function for fetching row arrays
• “$result” is the result returned by the mysqli_query function.

Example of PHP and MySQL Program:


<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “school_DB”;
$connection = mysqli_connect(‘$servername ‘, ‘$username’, ‘$password’,’$dbname’);
if (mysqli_connect_errno())
{
echo “Failed to connect to MySQL: “ . mysqli_connect_error();
}
sql_stmt = “SELECT * FROM my_contacts”; //SQL select query
$result = mysqli_query($connection,$sql_stmt);//execute SQL statement
$rows = mysqli_num_rows($result);// get number of rows returned
if ($rows)
{
while ($row = mysqli_fetch_array($result))
{
echo ‘ID: ‘ . $row[‘id’] . ‘<br>’;
echo ‘Full Names: ‘ . $row[‘full_names’] . ‘<br>’;
echo ‘Gender: ‘ . $row[‘gender’] . ‘<br>’;
echo ‘Contact No: ‘ . $row[‘contact_no’] . ‘<br>’;
echo ‘Email: ‘ . $row[‘email’] . ‘<br>’;
echo ‘City: ‘ . $row[‘city’] . ‘<br>’;
echo ‘Country: ‘ . $row[‘country’] . ‘<br><br>’;
}
}
mysqli_close($connection); //close the database connection
?>
In the above code the SQL query retrieves two records from student table in school database. These records are
populated into client browser using PHP scripting language.

SQL Commands or Statements


In any type of RDBMS the statements can be categorized in the following types:
• DDL statements
These types of statements are written to create or alter database objects. Like CREATE, DROP and ALTER
statements
• DML statements
These types of statements are written to modify the state of database objects like INSERT, UPDATE, INSERT
INTO statements.
• DCL statements
These types of statements are used to provide or revoke rights on database objects like GRANT and REVOKE
statements.
• DQL statements
These types of SQL statements are used to fetch records from a database table like SELECT statement.

UCS, Tumkur Page 8


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Create a MySQL Database Using MySQLi


The CREATE DATABASE statement is used to create a database in MySQL.
The following examples create a database named "myDB":

Note: When you create a new database, you must only specify the first three arguments to the mysqli
object (servername, username and password).

Tip: If you have to use a specific port, add an empty string for the database-name argument, like this:
new mysqli("localhost", "username", "password", "", port)

Example
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

Create a MySQL Table Using MySQLi


The CREATE TABLE statement is used to create a table in MySQL. The table named "MyGuests", with five
columns: "id", "firstname", "lastname", "email" and "reg_date":

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
)
After the data type, specify other optional attributes for each column:
• NOT NULL - Each row must contain a value for that column, null values are not allowed
• DEFAULT value - Set a default value that is added when no other value is passed
• UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
• AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a new record is
added
• PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is
often an ID number, and is often used with AUTO_INCREMENT
Each table should have a primary key column (in this case: the "id" column). Its value must be unique for each
record in the table.

UCS, Tumkur Page 9


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

The following example shows how to create the table in PHP:


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// 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 (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

Performing basic database operation(DML) (Insert, Delete, Update, Select)

Insert Data Into MySQL Using MySQLi


After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
• The SQL query must be quoted in PHP
• String values inside the SQL query must be quoted
• Numeric values must not be quoted
• The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default update of
current_timesamp (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will
automatically add the value.

The following examples add a new record to the "MyGuests" table:


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

UCS, Tumkur Page 10


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>

Select Data From a MySQL Database


The SELECT statement is used to select data from one or more tables:

SELECT column_name(s) FROM table_name


or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name

Select Data with MySQLi


The following example selects the id, firstname and lastname columns from the MyGuests table and displays it
on the page.

The following example shows the same as the example above, in the MySQLi procedural way:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

UCS, Tumkur Page 11


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Code lines to explain from the example above:


First, we set up an SQL query that selects the id, firstname and lastname columns from the MyGuests table. The
next line of code runs the query and puts the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative
array that we can loop through. The while() loop loops through the result set and outputs the data from the id,
firstname and lastname columns.

Update Data In a MySQL Table Using MySQLi


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

Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which record or records that
should be updated. If you omit the WHERE clause, all records will be updated!

Let's look at the "MyGuests" table:


id firstname lastname Email reg_date

1 John Doe john@example.com 2014-10-22 14:26:15

2 Mary Moe mary@example.com 2014-10-23 10:22:30

The following examples update the record with id=2 in the "MyGuests" table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

Delete Data From a MySQL Table Using MySQLi


The DELETE statement is used to delete records from a table:
DELETE FROM table_name
WHERE some_column = some_value

UCS, Tumkur Page 12


III BCA (NEP) PHP and MySQL SUMA N | Dept. of CS

Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record or records that
should be deleted. If you omit the WHERE clause, all records will be deleted!

Let's look at the "MyGuests" table:


id firstname lastname Email reg_date

1 John Doe john@example.com 2014-10-22 14:26:15

2 Mary Moe mary@example.com 2014-10-23 10:22:30

3 Julie Dooley julie@example.com 2014-10-26 10:48:23

The following examples delete the record with id=3 in the "MyGuests" table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

*******************

UCS, Tumkur Page 13

You might also like