Dynamic Suggested List: HTML5 + jQuery + PHP + MySQL

Today lets build a dynamic suggested list input field using HTML5, jQuery, PHP and MySQL.

Dynamic-suggested-list-html5-jquery-php-mysql

We have 55 company names in our database table – and the import file(.sql) can be downloaded at the end of this tutorial page. By using jQuery we pass user input to suggest.php file and the result is embedded into index.html file.

Related read: Suggested Entries Using datalist Element: HTML5

HTML file
index.html

<!DOCTYPE HTML>
<html>
<head>
<title>Dynamic Auto-Suggestion using datalist element: HTML5</title>
<meta charset="utf-8"/>
<script src="jQuery.js"></script>
<script src="myScript.js"></script>
</head>
<body>
 
<form>
<input type="text" list="myCompanies" name="company" id="suggest" />
<datalist id="myCompanies">
 
</datalist>
</form>
 
</body>
</html>

Here we have included jQuery library file before our script myScript.js
We also have an input field of type text, with an id = suggest, name = company and list = myCompanies. And a datalist element is linked/associated with input field, by matching it’s id with the name of input field’s list attribute. The value for option tag will be filled by jQuery, using the results output by suggest.php file.

PHP file
suggest.php

< ?php

    $db         = mysqli_connect('localhost', 'root', '', 'search');
    
    $company    = $_GET['company'];
    
    $sql        = "SELECT name FROM table1 WHERE name like '$company%' ORDER BY name";
    
    $res        = $db->query($sql);
    
    if(!$res)
        echo mysqli_error($db);
    else
        while( $row = $res->fetch_object() )
            echo "<option value="".$row->name."">";
        
?>

Here we connect php file to database(search). Get the keyword entered by the user in the input field and form a sql query. By using query() method, we process it and finally format it the way we need it i.e., we wrap the company names inside option tag’s value attribute.

jQuery file
myScript.js

$(document).ready(function(){
    $("#suggest").keyup(function(){
        $.get("suggest.php", {company: $(this).val()}, function(data){
            $("datalist").empty();
            $("datalist").html(data);
        });
    });
});

For every keyup event on the input field we trigger jQuery method $.get() and pass the user input keys to suggest.php file and the result is collected back by the callback function and the result set is stored in a variable called data.

Now we first make sure to clear out previous data present inside datalist element i.e., we clear the previous results by removing any option tags present inside datalist element. Now we fill the datalist element with the new data/result output from suggest.php file.

Since we’re using jQuery here, page does not reload and the suggested entries looks real and spontaneous.

Here is the list of company names I’ve taken for this tutorial

3M
7-Eleven
Accenture
Acer
Adidas
Adobe systems
Amazon.com
AMD
AOL
Apache
Apple inc
Appolo group
Aricent
Ask.com
Asus
AT&T
Bank of America
BBC
BE Aerospace
BMC Software
Boeing
Bosch Brewing Company
Boston Acoustic
CA Technologies
Citrix Systems
Cognizant Technolog
Cognizant Technology Solutions
Convergys
Dell
Delphi
DHL
Divx Inc
eBay
EMC Corporation
Exelon
Facebook
Ford Motor Company
Fox Entertainment Group
GCI
GoDaddy
Goodrich Corporation
Google
Hawaiian Airlines
Hewlett-Packard
Honeywell
IBM
Intel
Johnson & Johnson
KFC
McDonalds
Microsoft
Motorola
Nvidia
Red Hat
Yahoo!

Video Tutorials: Dynamic Suggested List: HTML5 + jQuery + PHP + MySQL


[youtube https://www.youtube.com/watch?v=YqMtE8UO-xw]

YouTube Link: https://www.youtube.com/watch?v=YqMtE8UO-xw [Watch the Video In Full Screen.]


Note: For any older browsers which do not support datalist element or list attribute, it will simply fall back to text type input field and it doesn’t produce any error.

Per-Class Constants And Static Methods: PHP OOP

This video tutorial illustrates the concepts of Per-Class Constants and Static Methods in Object Oriented PHP. Per-Class Constants was introduced in PHP5.

Per-Class Constants
Unlike variables, constants doesn’t change/alter its value during the program execution.
They’re treated as fixed values. Something which doesn’t change in the course of execution.

Since its value remains constant for all the objects, there is no need of an object to be created in-order to access it. We can directly access it using the class name and :: operator and the constant name.

Per-Class Constant
Math.php

1
2
3
4
5
6
7
< ?php
class Math {
const pi = 3.14159;
}
 
       echo Math::pi;
?>

This would output, 3.14159

Static Method
There’re situations where we need to take something which is global to the class.
And there is no use of invoking the method for all objects of that class. In such a situation make use of static methods. This way, you need not instantiate the class to invoke the method.

Syntax to invoke static method: class name, :: operator, method name.

Static Method Invocation
Math.php

1
2
3
4
5
6
7
8
9
< ?php
class Math {
static function square($no)
{
echo "<br />".$no * $no;
}
                echo Math::square(10);
}
?>

This would output, 100

Per-Class Constants And Static Methods: PHP OOP


[youtube https://www.youtube.com/watch?v=0tpX377CEgw]

YouTube Link: https://www.youtube.com/watch?v=0tpX377CEgw [Watch the Video In Full Screen.]



For example,
Declare database connection method as static, so that you can directly use the class name instead of creating an instance of the class.
This way, you can connect to the database, but you don’t have access to other non-static methods of the same class!

Implementing Interfaces: PHP OOP

Video tutorial illustrates the concept of implementing interfaces in Object Oriented PHP.

We also show you, how it over comes the ambiguity issue of multiple inheritance.

Interfaces acts as placeholder or the blueprint for what you can create.
Interfaces provide the basic design for a class with zero implementation detail.
Interfaces define what methods a class must have ..and you can create other methods outside of these limitations too.

extend and implement
interface.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
< ?php
class A
{
public function display()
{
echo "I love Apple Products";
}
}
 
interface I
{
const COMPANY = "Technotip.com";
public function company();
public function display();
}
 
class B extends A implements I
{
function company()
{
echo "I Love BuySellAds and Technotip.com";
}
 
function display()
{
echo "Microsoft & Oracle";
}
}
 
$obj = new B();
$obj->company();
?>

This would output I Love BuySellAds and Technotip.com

Accessing Constant Variable
To access the constant variable present inside interface, use the class name followed by scope resolution operator and then the constant variable name:
B::COMPANY

Implementing Interfaces: PHP OOP


[youtube https://www.youtube.com/watch?v=iOfpmXph5EU]

YouTube Link: https://www.youtube.com/watch?v=iOfpmXph5EU [Watch the Video In Full Screen.]



In multiple inheritance you have two parent classes. If both of them have a method with same name, signature and you don’t even override it in the child / derived class, then PHP engine will have no way to know which method to use.

multiple-inheritance-classB-classC-to-classA


In interface, you HAVE TO (must) override the methods present in interface class while implementing it. Hence solving the ambiguity issue.

Note:
All methods declared in an interface must be public.
All variables in interface must be constant.
Interfaces cannot be instantiated.
Object Oriented PHP only supports Single Inheritance. i.e., you can have only one parent class.
You can implement more than one interface. Use comma separation to implement more than one interfaces.

Ex 1:
interface A { }
interface B { }
class C implements A, B { }

Ex 2:
class D { }
interface A { }
interface B { }
class C extends D implements A, B { }

Multiple And Hybrid Inheritance: PHP OOP

Video tutorial to illustrate Inheritance mechanism in Object Oriented PHP.

Inheritance is a mechanism where objects of one class acquires the properties of objects of another class.

PHP supports only single inheritance.
i.e., a class should inherit from only one parent class / base class. If it inherits from more than one base class, then it’s not a valid inheritance in PHP.

Thus, multiple inheritance and hybrid inheritance is not supported in Object Oriented PHP.

Single Inheritance
class B inherits from class A

single-inheritance-classA-to-classB

class C inherits from class B which in turn inherits from class A

single-inheritance-classA-to-classB-to-classC

class B and class C inherits from class A

single-inheritance-classA-to-classB-and-classC

Invalid Inheritance in PHP
Multiple Inheritance
class A inherits from two base/parent classes B and C

multiple-inheritance-classB-classC-to-classA

Hybrid Inheritance
class B and C inherits from a single base/parent class, i.e., class A
again, class D inherits from class B and class C

hybrid-inheritance

Single Inheritance: class B and class C inherits from class A

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
< ?php
class A
{
function display()
{
echo "Apple, Google, Oracle, Microsoft";
}
}
 
class B extends A
{
 
}
 
class C extends A
{
 
}
 
$obj = new C(); 
//$obj = new A(); 
//$obj = new B(); 
$obj->display();
?>

This should output
Apple, Google, Oracle, Microsoft

Multiple And Hybrid Inheritance: PHP OOP


[youtube https://www.youtube.com/watch?v=vEubH2KVgYk]

YouTube Link: https://www.youtube.com/watch?v=vEubH2KVgYk [Watch the Video In Full Screen.]



Try yourselves:
If you try to extend class A and class B to class C, it’ll through fatal error.

Related Read:
Single Inheritance: PHP OOP

Note:
So, technically you can’t extend/inherit from more than 1 base/parent class.
To overcome this situation, we can make use of Interfaces.
Interfaces in PHP works similar to that of Java. We’ll teach interfaces in another video tutorial, so stay subscribed.

Preventing Inheritance and Overriding with final: PHP OOP

Video tutorial illustrating, how to prevent inheritance and overring using final keyword, in Object Oriented PHP.

stop-sign

In this program, we take two classes A and B, and then extend Class A to Class B.
Now using the final keyword, we’ll show how to avoid extending class A to class B or any other classes. Next, we’ll also show, how to use final keyword to prevent method overriding.

Avoiding Inheritance

<?php
 final class A
 {
 
 }
 
 class B extends A
 {
 
 }
?>

This through’s following fatal error:

Fatal error: Class B may not inherit from final class (A) in C:\wamp\www\OOP\final.php on line 16

So, using the keyword final infront of the class name prevents it from inheritance.

Avoiding Overriding of method

<?php
class A
{
final function display()
{
echo "Inside class A";
}
}
 
class B extends A
{
function display()
{
echo "Inside class B";
}
}
?>

This through’s following fatal error:

Fatal error: Cannot override final method A::display() in C:\wamp\www\OOP\final.php on line 16

So, using the keyword final infront of the method name prevents it from being overriden.

Related:
If you want to know the basics of Inheritance and Overriding, go through this short notes before proceeding
Single Inheritance: PHP OOP
Overriding: PHP OOP

Video Tutorial: Preventing Inheritance and Overriding with final: PHP OOP


[youtube https://www.youtube.com/watch?v=NXsD908RSVE]

YouTube Link: https://www.youtube.com/watch?v=NXsD908RSVE [Watch the Video In Full Screen.]


Sometimes preventing inheritance and avoiding overriding of certain methods becomes necessary inorder to maintain the sanity or data integrity while coding.