Simple Search Using PHP and MySQL
I'm going to show you how to create simple search using PHP and MySQL. You'll learn:
- How to use GET and POST methods
- Connect to database
- Communicate with database
- Find matching database entries with given word or phrase
- Display results
Preparation
You should have Apache, MySQL and PHP installed and running of course (you can use XAMPP for different platforms or WAMP for windows, MAMP for mac) or a web server/hosting that supports PHP and MySQL databases.
Let's create database, table and fill it with some entries we can use for search:
- Go to phpMyAdmin, if you have server on your computer you can access it at http://localhost/phpmyadmin/
- Create database, I called mine tutorial_search
- Create table I used 3 fields, I called mine articles.
- Configuration for 1st field. Name: id, type: INT, check AUTO_INCREMENT, index: primary
INT means it's integer
AUTO_INCREMENT means that new entries will have other(higher) number than previous
Index: primary means that it's unique key used to identify row
AUTO_INCREMENT means that new entries will have other(higher) number than previous
Index: primary means that it's unique key used to identify row
- 2nd field: Name: title, type: VARCHAR, length: 225
VARCHAR means it string of text, maximum 225 characters(it is required to specify maximum length), use it for titles, names, addresses
length means it can't be longer than 225 characters(you can set it to lower number if you want)
length means it can't be longer than 225 characters(you can set it to lower number if you want)
- 3rd field: Name: text, type: TEXT
TEXT means it's long string, it's not necessary to specify length, use it for long text.
- Fill the table with some random articles(you can find them on news websites, for example: CNN, BBC, etc.). Click insert on the top menu and copy text to a specific fields. Leave "id" field empty. Insert at least three.
It should look something like this:
- Create a folder in your server directory and two files: index.php and search.php (actually we can do all this just with one file, but let's use two, it will be easier)
- Fill them with default html markup, doctype, head, etc.
1
2
3
4
5
6
7
8
9
10
| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> < head > < title >Search</ title > < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" /> </ head > < body > </ body > </ html > |
- Create a form with search field and submit button in index.php, you can use GET or POST method, set action to search.php. I used "query" as name for text field
GET - means your information will be stored in url (http://localhost/tutorial_search/search.php?query=yourQuery)
POST - means your information won't be displayed it is used for passwords, private information, much more secure than GET
POST - means your information won't be displayed it is used for passwords, private information, much more secure than GET
1
2
3
4
| < form action = "search.php" method = "GET" > < input type = "text" name = "query" /> < input type = "submit" value = "Search" /> </ form > |
Ok, let's get started with php.
- Open search.php
- Start php (<?php ?>)
- Connect to a database(read comments in following code)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| <?php mysql_connect( "localhost" , "root" , "" ) or die ( "Error connecting to database: " .mysql_error()); /* localhost - it's location of the mysql server, usually localhost root - your username third is your password if connection fails it will stop loading the page and display an error */ mysql_select_db( "tutorial_search" ) or die (mysql_error()); /* tutorial_search is the name of database we've created */ ?> |
You can go and check if there is no errors.
- Now go to the <body></body> part of the page
- I'm using GET method, if you want to use POST, just use $_POST instead of $_GET
- Also some functions to make it more secure. Read comments in the code
- Send query to database
- Check if there is any results
- If there is any, post them using while loop
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
33
34
35
36
37
38
39
40
41
42
43
44
| <?php $query = $_GET [ 'query' ]; // gets value sent over search form $min_length = 3; // you can set minimum length of the query if you want if ( strlen ( $query ) >= $min_length ){ // if query length is more or equal minimum length then $query = htmlspecialchars( $query ); // changes characters used in html to their equivalents, for example: < to > $query = mysql_real_escape_string( $query ); // makes sure nobody uses SQL injection $raw_results = mysql_query("SELECT * FROM articles WHERE (`title` LIKE '%".$query."%' ) OR (`text` LIKE '%".$query."%' )") or die (mysql_error()); // * means that it selects all fields, you can also write: `id`, `title`, `text` // articles is the name of our table // '%$query%' is what we're looking for, % means anything, for example if $query is Hello // it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query' // or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query' if (mysql_num_rows( $raw_results ) > 0){ // if one or more rows are returned do following while ( $results = mysql_fetch_array( $raw_results )){ // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop echo "<p><h3>" . $results [ 'title' ]. "</h3>" . $results [ 'text' ]. "</p>" ; // posts results gotten from database(title and text) you can also show id ($results['id']) } } else { // if there is no matching rows do following echo "No results" ; } } else { // if query length is less than minimum echo "Minimum length is " . $min_length ; } ?> |
Done!
Now it works. Try different words, variations, editing code, experiment. I'm adding full code of both files in case you think you've missed something. Feel free to ask questions or ask for tutorials.
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> < head > < title >Search</ title > < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" /> < link rel = "stylesheet" type = "text/css" href = "style.css" /> </ head > < body > < form action = "search.php" method = "GET" > < input type = "text" name = "query" /> < input type = "submit" value = "Search" /> </ form > </ body > </ html > |
search.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
| <?php mysql_connect( "localhost" , "root" , "" ) or die ( "Error connecting to database: " .mysql_error()); /* localhost - it's location of the mysql server, usually localhost root - your username third is your password if connection fails it will stop loading the page and display an error */ mysql_select_db( "tutorial_search" ) or die (mysql_error()); /* tutorial_search is the name of database we've created */ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" > <head> <title>Search results</title> <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" /> <link rel= "stylesheet" type= "text/css" href= "style.css" /> </head> <body> <?php $query = $_GET [ 'query' ]; // gets value sent over search form $min_length = 3; // you can set minimum length of the query if you want if ( strlen ( $query ) >= $min_length ){ // if query length is more or equal minimum length then $query = htmlspecialchars( $query ); // changes characters used in html to their equivalents, for example: < to > $query = mysql_real_escape_string( $query ); // makes sure nobody uses SQL injection $raw_results = mysql_query("SELECT * FROM articles WHERE (`title` LIKE '%".$query."%' ) OR (`text` LIKE '%".$query."%' )") or die (mysql_error()); // * means that it selects all fields, you can also write: `id`, `title`, `text` // articles is the name of our table // '%$query%' is what we're looking for, % means anything, for example if $query is Hello // it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query' // or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query' if (mysql_num_rows( $raw_results ) > 0){ // if one or more rows are returned do following while ( $results = mysql_fetch_array( $raw_results )){ // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop echo "<p><h3>" . $results [ 'title' ]. "</h3>" . $results [ 'text' ]. "</p>" ; // posts results gotten from database(title and text) you can also show id ($results['id']) } } else { // if there is no matching rows do following echo "No results" ; } } else { // if query length is less than minimum echo "Minimum length is " . $min_length ; } ?> </body> </html> |
0 comments:
Post a Comment