MySQL – SEARCH Form with HTML and PHP

You can create an HTML form that allows you to search records in your MySQL Tables and print the results in a web browser.

In these project we use LIKE and wildcards for the query so that users do not have to have an exact match for results to be provided.

Simple Search Form Project

search.html

<html>
<body>

<form action="phpSearch.php" method="post">
Search <input type="text" name="search"><br>
<input type ="submit">
</form>

</body>
</html>

phpSearch.php

<?php

$search = $_POST['search'];

$servername = "localhost";
$username = "bob";
$password = "123456";
$db = "classDB";

$conn = new mysqli($servername, $username, $password, $db);

if ($conn->connect_error){
	die("Connection failed: ". $conn->connect_error);
}

$sql = "select * from students where name like '%$search%'";

$result = $conn->query($sql);

if ($result->num_rows > 0){
while($row = $result->fetch_assoc() ){
	echo $row["name"]."  ".$row["age"]."  ".$row["gender"]."<br>";
}
} else {
	echo "0 records";
}

$conn->close();

?>

Option Box Search Form Project

searchoption.html

<html>
<body>

<form action="phpSearchOption.php" method="post">
Search <input type="text" name="search"><br>

Column: <select name="column">
	<option value="name">Name</option>
	<option value="age">Age</option>
	<option value="gender">Gender</option>
	</select><br>
<input type ="submit">
</form>

</body>
</html>

phpSearchOption.php

<?php

$search = $_POST['search'];
$column = $_POST['column'];

$servername = "localhost";
$username = "bob";
$password = "123456";
$db = "classDB";

$conn = new mysqli($servername, $username, $password, $db);

if ($conn->connect_error){
	die("Connection failed: ". $conn->connect_error);
}

$sql = "select * from students where $column like '%$search%'";

$result = $conn->query($sql);

if ($result->num_rows > 0){
while($row = $result->fetch_assoc() ){
	echo $row["name"]."  ".$row["age"]."  ".$row["gender"]."<br>";
}
} else {
	echo "0 records";
}

$conn->close();

?>

Be the first to comment

Leave a Reply