Introduction
In this article I will explain the MySQL "Like" operator in PHP. The MySQL Like operator is based on pattern matching and commonly used to select data based on pattern matching. The LIKE operator allows you to select data from a MySQL database table and therefore this operator is used in the WHERE clause. MySQL provides two characters for using with the LIKE operator, such as percentage "%" and underscore "_". In this article you can learn how to use the Like operator in MySQL.
- Percentage allows you to match with any characters or string but
- Underscore allows you to match with any one character.
Example
Like operator with percentage
Use of the like operator with a where clause. In this query you will see that I selected data from the database using like with percentage.
<html>
<head>
<style>
table
{
border-style:solid;
border-width:2px;
border-color:gray;
}
</style>
</head>
<body bgcolor="#C2DAD3">
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("examples", $con);
$result = mysql_query("SELECT id, name, salary FROM employee where name like 'n%'");
echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>salary</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['salary'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
Your table is:
If you want to fetch data from the name field starting with the character "n%" then you can do it with:
SELECT id, name, salary FROM employee where name like 'n%';
Output
If you want to fetch data from the name field ending with the character "%d" then you can do it with:
SELECT id, name, salary FROM employee where name like '%d';
Output
If you want to fetch data from the name field starting and ending with the character "%a%" then you can do it with:
SELECT id, name, salary FROM employee where name like '%a%';
Output
Like operator with Underscore
If you want to fetch data from the name field starting with "t" and ending with "m" with any single character between then you can do it with:
SELECT id, name, salary FROM employee where name like 't_m';
Output