Skip to main content

Practical-21

Write a PHP program for delete, update record from the database​

Introdution​

Are you looking to learn how to modify and delete records in a database with a PHP program? 🤔 With this tutorial, you’ll learn the basics of creating a PHP program. You’ll need to have a basic knowledge of HTML, JavaScript and databases such as MySQL. We will show you how to create a program that can delete or update records in the database. You will also get some best practices and tips to ensure the program runs smoothly and the data is secure. Get ready to start programming! 😃

Code​

$dbhost = "localhost";
$dbuser = "username";
$dbpass = "password";
$dbname = "database_name";

// Establish a connection to the database
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);

// Check connection
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}

// Get variables from form submission
$id = $_POST['id'];
$status = $_POST['status'];

// Delete record query
$sql1="DELETE FROM table_name WHERE id='$id'";
if (mysqli_query($conn, $sql1)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}

// Update record query
$sql2="UPDATE table_name SET status='$status'
WHERE id='$id'";
if (mysqli_query($conn, $sql2)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}

// Close the connection
mysqli_close($conn);

Output​

Record deleted successfully. Record updated successfully.

Explanation

The code is a PHP program for delete, update record from the database. It establishes a connection to the database using the $dbhost, $dbuser, $dbpass and $dbname variables. After that, it gets the variables from the form submission and uses them to construct a SQL query for either deleting or updating the record. Lastly, it checks for errors and closes the connection when it's finished.

Get Help​