MySQL Like Operator in PHP

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.

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.

  1. <html>  
  2. <head>  
  3. <style>  
  4. table  
  5. {  
  6. border-style:solid;  
  7. border-width:2px;  
  8. border-color:gray;  
  9. }  
  10. </style>  
  11. </head>  
  12. <body bgcolor="#C2DAD3">  
  13. <?php  
  14. $con = mysql_connect("localhost","root","");  
  15. if (!$con)  
  16.   {  
  17.   die('Could not connect: ' . mysql_error());  
  18.   }  
  19. mysql_select_db("examples"$con);  
  20. $result = mysql_query("SELECT id, name, salary FROM employee where name like 'n%'");  
  21. echo "<table border='1'>  
  22. <tr>  
  23. <th>id</th>  
  24. <th>name</th>  
  25. <th>salary</th>  
  26. </tr>";  
  27. while($row = mysql_fetch_array($result))  
  28.   {  
  29.   echo "<tr>";  
  30.   echo "<td>" . $row['id'] . "</td>";  
  31.   echo "<td>" . $row['name'] . "</td>";  
  32.   echo "<td>" . $row['salary'] . "</td>";  
  33.   echo "</tr>";  
  34.   }  
  35. echo "</table>";  
  36. mysql_close($con);  
  37. ?>  
  38. </body>  
  39. </html>  
Your table is:

image1.jpg

If you want to fetch data from the name field starting with the character "n%" then you can do it with:

  1. SELECT id, name, salary FROM employee where name like 'n%';  
Output

image2.jpg

If you want to fetch data from the name field ending with the character "%d" then you can do it with:

  1. SELECT id, name, salary FROM employee where name like '%d';  
Output

image3.jpg

If you want to fetch data from the name field starting and ending with the character "%a%" then you can do it with:

  1. SELECT id, name, salary FROM employee where name like '%a%';  
Output

image4.jpg

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:

  1. SELECT id, name, salary FROM employee where name like 't_m';  
Output

image5.jpg