I want to search and filter data in a table but I don't know how to do it as I am currently learning php. This is the php script I use to search the data
<?php require('./conn.php'); if (isset($_POST['search'])) { $valueToSearch = $_POST['query']; // search in all table columns // using concat mysql <function></function> $query = "SELECT * FROM `user_2` WHERE CONCAT(`firstname`, `lastname`) LIKE '%" . $valueToSearch . "%'"; $search_result = filterTable($query); } else { $query = "SELECT * FROM `user_2`"; $search_result = filterTable($query); } // function to connect and execute the query function filterTable($query) { $connect = mysqli_connect("localhost", "root", "", "info"); $filter_Result = mysqli_query($connect, $query); return $filter_Result; } ?>
This is my input field search
<form action="index.php" method="post" enctype="multipart/data-form"> <table align="center"> <tr> <td> Search: <input type="text" name="query"> <input type="submit" value="search" name="search"> </td> </tr> </table> </form>
This is my table in php, I want to display the data I want to search in this table
<table align="center" border="5" cellspacing="0" width="500"> <tr> <th>First Name</th> <th>Last Name</th> <th>Update</th> <th>Delete</th> </tr> <?php $sql = "SELECT * FROM user_2"; $stmt = $conn->prepare($sql); $stmt->execute(); foreach ($stmt as $result) : ?> <tr> <td align="center"><?php echo $result['firstname'] ?></td> <td align="center"><?php echo $result['lastname'] ?></td> <td align="center"> <a href="./edit.php?user2_id=<?php echo $result['user2_id'] ?>">Edit</a> </a> </td> <td align="center"> <a href="./delete.php?user2_id=<?php echo $result['user2_id'] ?>" onclick="return confirm('Are you sure you want to delete this user?')"> Delete</td> </tr> <?php endforeach; ?> </table>
You may want to use AJAX to send the request to the server and rebuild the table based on the returned data. Here's a quick hashed together example, not tested yet but might work. The entire review should explain what is going on. Made various minor corrections to the HTML and used the css I referenced in the comments to center align the form content.