Create Search Form with PHP
GOAL
Today’s goal is to create search form to find the name from the database.

Environment
Windows10
XAMPP 7.4.10
Method
This is an adjusted version of the code in “Access MySQL with PHP in XAMPP“. So please check the article first.
Search form
Use post method and the form is named “word” as below.
<form action="" method="POST"> <label>Name:</label> <input type="text" name="word" /> <input type="submit" value="Search" /> </form>
Connect database
Connect database according to “Access MySQL with PHP in XAMPP“.
<?php $dsn = 'mysql:host=localhost;dbname=photo_sharing'; $username = 'root'; $password = '********'; if ($_POST) { // when the word is submitted $dbh = new PDO($dsn, $username, $password); $search_word = $_POST['word']; // execute sql and get data here
Get and display the result
SQL
Use select statement to get data from the database. In this case, use pattern matching by LIKE operator to get the item whose name starts with input word. (reference: SQL WHERE LIKE Statement)
$sql ="select * from user where name like '".$search_word."%'"; $sth = $dbh->prepare($sql); $sth->execute(); $result = $sth->fetchAll(); if($result){ foreach ($result as $row) { echo $row['name']." "; echo $row['age']; echo "<br />"; } } else{ echo "not found"; }
Code
The following is the completed code.
index.php
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body> <div>Search user name</div> <form action="" method="POST"> <label>Name:</label> <input type="text" name="word" /> <input type="submit" value="Search" /> </form> <?php $dsn = 'mysql:host=localhost;dbname=photo_sharing'; $username = 'root'; $password = '********'; if ($_POST) { try { $dbh = new PDO($dsn, $username, $password); $search_word = $_POST['word']; if($search_word==""){ echo "input search word"; } else{ $sql ="select * from user where name like '".$search_word."%'"; $sth = $dbh->prepare($sql); $sth->execute(); $result = $sth->fetchAll(); if($result){ foreach ($result as $row) { echo $row['name']." "; echo $row['age']; echo "<br />"; } } else{ echo "not found"; } } }catch (PDOException $e) { echo "<p>Failed : " . $e->getMessage()."</p>"; exit(); } } ?> </body> </html>
Result
