How to SELECT LIKE from a table.
TAGS: SQL, LIKE, PHP, MySQL


Now, in this post, we will look at the SQL operator 'LIKE'.
No, it's not about facebook, but it's about finding content from your database using words, or part of words, for searching, where you will get results, containing your seachphrase.

Imagine searching for '%angel%'. With LIKE you will get 'Angel', 'Angels', 'Los Angeles', 'Archangel', and so on.

If you use this; '%ing' you will search for word ending in 'ing'.
On the other hand, if you do this; 'be%' you search for words beginning with 'be'.

If you want to find all words with the phrase 'tt', you can do this; '%tt%'. Then your result will be words with 'tt' somewhere in it. Like getting, lotto, betting, setting, etc.

Her is an example that you can try, using the database you have created in the beginning of these blogs.

<?php 
$con = mysqli_connect('127.0.0.1', 'root', 'Your_Passwords', 'dbname'); 

if (mysqli_connect_errno()) { 
  echo 'Error connecting to DB'; 
} 

$SQL_String = mysqli_query(
$con, 'SELECT * FROM contacts WHERE Lastname LIKE '%sen''); 

while($row = mysqli_fetch_array($SQL_String))  { 
  echo $row['AutoID'] . ': ' . $row['Firstname'] . ' ' . $row['Lastname'] . '
'; } mysqli_close ($con); ?>


Notice that if your table does not contain any Lastnames that ends with the string 'sen', then you will not get any result. Either try to add some rows to the table, as seen in an ealier posting, or change the %LIKE% pattern in the SQL string, in the above codesnippet.

Now we will go from handling databases to look at other things that you can do with PHP. In the next blog I will give an example on how to generate random passwords.