I created a very basic and simple search programming that displays the first and last name of the entered username in a fetched row. It was successful, but only if the entered username matches the exact characters and length of the username in the database. I want my code to read it even if it isn't complete; for example, the username in the database is "baymax16", and the entered username is "max16", I want it to return true since some characters matches. I used preg_match()
, but there's an error. Should I use preg_match()
? If yes, how should I use it correctly? If no, what should I use?
<?php
$db = new PDO('mysql:host=127.0.0.1;dbname=sample;charset=utf8', 'root', '');
if(isset($_POST['search'])) {
$search = $_POST['search'];
$query = $db->prepare("SELECT * FROM search WHERE username=:username");
$query->execute(['username' => $search]);
$row = $query->fetch(PDO::FETCH_OBJ);
if(count($row)) {
if(preg_match($search, $row)) {
echo $row->firstname . ' ' . $row->lastname;
}
}
}
Your query there:
SELECT * FROM search WHERE username=:username
is telling the database to extract the data IFF the supplied string is EQUAL to the string that exists in the database.
Why not use LIKE
operator in the query?
SELECT * FROM search WHERE username LIKE CONCAT('%', :username,'%');