This tutorial will help you that how to perform insert, update and delete operations using PHP & MySQLi, using short functions and so low code.
I have create on insert.php file and i have all the program code write in this single file
insert.php
following are the my php and html code:
<?php
include "db.php";
if(isset($_POST['submit']) && $_POST['action'] == "add"){
extract($_POST);
$que = $con->query("insert into student(stud_name,email,password) values('$nm','$email','$pass')");
if($que){header('location:insert.php');exit();}
else{ echo "not added";}
}
if(isset($_GET['delete'])){
$del_res= $con->query("delete from student where id =".$_GET['delete']);
header('location:insert.php');
exit();
}
if(isset($_GET['edit'])){
$get_rec = $con->query('select * from student where id='.$_GET['edit'])->fetch_assoc();
//print_r($get_rec);
}
if(isset($_POST['submit']) && $_POST['action'] == "edit"){
extract($_POST);
$que = $con->query("update student set stud_name = '$nm',email='$email',password='$pass' WHERE id=".$_GET['edit']);
header('location:insert.php');
exit();
}
$result = $con->query("select * from student");
?>
<html>
<body>
<form action="" method="post">
<div>name :<input type="text" name="nm" value="<?= (isset($get_rec['stud_name'])) ? $get_rec['stud_name'] : ''; ?>"></div>
<div>email :<input type="email" name="email" value="<?= (isset($get_rec['email'])) ? $get_rec['email'] : ''; ?>"> </div>
<div>password :<input type="password" name="pass" value="<?= (isset($get_rec['password'])) ? $get_rec['password'] : ''; ?>"></div>
<div>
<input type="hidden" name="action" value="<?= isset($_GET['edit']) ? "edit":"add" ?>">
<input type="submit" name="submit">
<input type="reset" name="reset">
</div>
</form>
<table border='1' cellpadding='10' cellspacing='0'>
<tr>
<th>NO</th>
<th>Name</th>
<th>email</th>
<th>password</th>
<th>action</th>
</tr>
<?php
$i=1;
while($row = $result->fetch_assoc())
{
?>
<tr>
<td><?php echo $i; ?></td>
<td><?= $row['stud_name']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['password']; ?></td>
<td><a href="insert.php?delete=<?php echo $row["id"] ;?>">Delete</a> | <a href="insert.php?edit=<?php echo $row["id"] ;?>">EDIT</a></td>
</tr>
<?php
$i++;
}
?>
</table>
</body>
</html>