Crud operation in php refer to the four basic functions used in php – databases: Create, Read, Update, and Delete. In PHP and MySQL, CRUD operations are commonly used for building dynamic web applications that require the management of data.
index.php <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> </head> <div style="padding:30px"> <h3>Registration Form</h3> <br/> <form method="post" action="insert.php" enctype="multipart/form-data"> <div> <label>Name</label> <input type="text" name="name" /> </div><br/> <div> <label>Email</label> <input type="text" name="email" /> </div><br/> <!-- <div> <label>Upload Image</label> <input type="file" name="user_img"> </div> --> <br/> <button type="submit">Submit</button> </form> </div> <br/> <div style="padding:30px"> <?php if ( isset($_GET['success']) && $_GET['success'] == 1 ) { echo "Success !"; } ?> <table> <thead> <tr> <th>Name</th> <th>Email</th> <th>Action</th> </tr> </thead> <tbody> <?php include('dbcon.php'); $sql = "SELECT * FROM students"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { ?> <tr> <td><?php echo $row['name']; ?></td> <td><?php echo $row['email']; ?></td> <td><a href="edit.php?id=<?php echo $row['id']; ?>">Edit</a> <a href="delete.php?id=<?php echo $row['id']; ?>">Delete</a></td> </tr> <?php } } else{ echo "0 results"; } $conn->close(); ?> </tbody> </table> </div>
dbcon.php <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "php"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } ?>
insert.php <?php $name = $_POST['name']; $email = $_POST['email']; include('dbcon.php'); $sql = "INSERT INTO students (name, email) VALUES ('$name', '$email')"; if (mysqli_query($conn, $sql)) { Header( 'Location: index.php?success=1' ); } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
update.php <?php include('dbcon.php'); $id = $_POST['id']; $name = $_POST['name']; $email = $_POST['email']; $sql = "UPDATE students SET name='$name', email='$email' WHERE id=$id"; if ($conn->query($sql) === TRUE) { Header( 'Location: test.php?success=1' ); } else { echo "Error updating record: " . $conn->error; } $conn->close(); ?>
delete.php <?php include('dbcon.php'); $id = $_GET['id']; $sql = "DELETE FROM students WHERE id=$id"; if ($conn->query($sql) === TRUE) { Header( 'Location: test.php?success=1' ); } else { echo "Error deleting record: " . $conn->error; } $conn->close(); ?>