How to Delete Data in the Database Using PHP/MySQLi

Today, you will learn How to Delete Data in the Database Using PHP/MySQLi. This method will show you on how to Delete Data into Database with the use of delete query statement in PHP and MySQLi.

 

Below are following step by step guide on how to Delete Data in the Database Using PHP and MySQLi.

 

Lets Begin:

 

First Step: Create a MySQL Database and name it “userdb“.

Second: Do the following code for creating a table in the database that you have created.

[mysql]

CREATE TABLE IF NOT EXISTS `tbluser` (
`UserID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(30) NOT NULL,
`Username` varchar(30) NOT NULL,
`Pass` varchar(90) NOT NULL,
PRIMARY KEY (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

[/mysql]

Third Step:Do the Insert Query to insert the data in the table that you have created.

[mysql]

INSERT INTO `tbluser` (`UserID`, `Name`, `Username`, `Pass`) VALUES
(1, ‘Janno Palacios’, ‘janobe’, ‘admin’),
(2, ‘Joken villanueva’, ‘joken’, ‘joken’),
(3, ‘kejie palacios’, ‘kenjie’, ‘kenjie’);

[/mysql]

Fourth Step: Create a landing page and name it “index.php“.

Fifth Step: Create a CSS layout of the table.

[css]
.table{
width: 100%;
border: solid 1px #ddd;
}
.table tr,
.table td {
position: inherit;
border: solid 1px #ddd;
}

[/css]

Sixth Step: Do the following code for retrieving data in the database.

[php]

<table class=”table”>
<tr>
<td>User ID</td>
<td>Name</td>
<td>Username</td>
<td>Action</td>
</tr><?php$server=”localhost”;
$userid =”root”;
$Password = “”;
$myDB = “userdb”;

$con = mysqli_connect($server,$userid,$Password,$myDB);

if (mysqli_connect_errno()) {
echo “Failed to connect to MySQL: ” . mysqli_connect_error();
}
$sqli=”SELECT * FROM tbluser”;
$result=mysqli_query($con,$sqli) or die(“query error”);
while($row=mysqli_fetch_array($result)) {
echo ‘<tr>’;
echo ‘<td>’.$row[‘UserID’].'</td>’;
echo ‘<td>’.$row[‘Name’].'</td>’;
echo ‘<td>’.$row[‘Username’].'</td>’;
echo ‘<td><a href=”index.php?id=’.$row[‘UserID’].'”>Delete</a></td>’;
echo ‘</tr>’;
}
}
?>
</table>

[/php]

Seventh Step: Do the following code for deleting data in the database.

[php]

if(isset($_GET[‘id’])){

$id = $_GET[‘id’];

$sqli = “DELETE FROM `tbluser` WHERE `UserID`='{$id}'”;
$res = mysqli_query($con,$sqli);

if ($res) {
# code…
header(‘Location: index.php’);
}

}

[/php]

If you have any questions or suggestion about How to Delete Data in the Database Using PHP/MySQLi, please feel free to contact us at our contact page.You can subscribe this site to see more of my tutorials.

Leave a Comment