WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search


Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder



Go Back Add a Comment Send this Article to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES SUBMIT AN ARTICLE PRINT
Title : PHP: A simple MySQL search
Categories : PHP, MySQL, Beginner Guides, To PHP, To MySQL
Rafi Ton
Rafi Ton
Date : 2000-05-13
Grade : 4 of 5 (graded 11 times)
Viewed : 244021
Search : More Articles by Rafi Ton
Action : Grade This Article
Tools : My Favotite Articles


Submit your own code examples 
 


Introduction



One of the most important advantages of creating a database driven sites is the ability to perform search queries on the database. Could you imagine searching WeberDev.com if it was written using plain HTML? Not that it couldn't be done, just we would have to rebuild an index of all the pages every time someone adds an example, article and so on.



Now, performing searches on a database driven site is a totally different story (and thankfully much easier).



Grocery list





In order to understand and work a bit with searches we will need a small MySQL driven site. I will use the structure we built at my "Beginners guide to PHP/MySQL - Creating a simple guest book" article. Actually, we will write a search page for the guest book described in the above tutorial, so go on and take a brief look at the PHP code for the guest book, I'm waiting.



Notice that we have a file named links.x, which holds the links to the guest book pages. We will modify it slightly to include a link to the search page (the third <li> statement).



Links.x:


<p></p>
<ul>
<li><a href="index.php3">Display entries</a>
<li><a href="add.php3">Add new entry</a>
<li><a href="search.php3">Search the guest book</a>
</ul>


Ok, done with that.



Searching the database



To tell the truth, we don’t actually search the database, but rather select records from it that correspond to a string we choose. Lets assume we want to search all the records where the users' name matches the search string:



Search.php3:


<html>
<head><title>Searching the Guest Book</title>
</head>
<body bgcolor=#ffffff>
<h1>Searching the Database</h1>
<form method="post" action="srch.php3">
<table width=90% align=center>
<tr><td>search for:</td><td><input type=text name='search' size=60 maxlength=255></td></tr>
<td></td><td><input type=submit></td></tr>
</table>
</form>
<?php include ('links.x');?>
</body>
</html>


This html is rather simple. Just a small form that sends a search string variable to srch.php3.



Srch.php3:


<?
if ($search) // perform search only if a string was entered.
{
mysql_connect() or die ("Problem connecting to Database");

$query = "select * from visitors WHERE Name='$search'";

$result = mysql_db_query("guest_book", $query);

if (
$result)
{
echo
"Here are the results:<br><br>";
echo
"<table width=90% align=center border=1><tr>
<td align=center bgcolor=#00FFFF>Visit time and date</td>
<td align=center bgcolor=#00FFFF>User Name</td>
<td align=center bgcolor=#00FFFF>Last Name</td>
<td align=center bgcolor=#00FFFF>Email</td>
</tr>"
;

while (
$r = mysql_fetch_array($result)) { // Begin while
$ts = $r["TimeStamp"];
$name = $r["Name"];
$last = $r["Last"];
$email = $r["email"];
$comment = $r["comment"];
echo
"<tr>
<td>$ts</td>
<td>$name</td>
<td>$last</td>
<td>$email</td></tr>
<tr> <td colspan=4 bgcolor=\"#ffffa0\">$comment</td>
</tr>"
;
}
// end while
echo "</table>";
} else { echo
"problems...."; }
} else {
echo
"Search string is empty. <br> Go back and type a string to search";
}
include (
'links.x');
?>


Some explanations. This scripts performs the following tasks:



  1. Checks whether a string was entered.
  2. Retrieves all the records that match the search string.
  3. Prints all the retrieved records in a formatted table.

Clearing all the mumbo jumbo, the actual code that we need to work on is:





$query = "select * from visitors WHERE Name='$search'";


Yes, this line does all the work. We will play with it a bit later.



Ok, this query gets all the records where the Name field is equal to the string search. Please note that an exact match is needed.



Lets assume we want to search for a partial string match (i.e. where the search string appears in the filed but as part of the string and not an exact match). We will have to modify the script as follows:


$srch="%".$search."%";
$query = "select * from visitors WHERE Name LIKE' $srch'";


The LIKE comparison argument will return '1' if the Name field has a partial value of $search. Note that I modified $search and added "%" on both ends. This allows to search for the search to ignore the leading characters and the characters following the search string.



Ok, now lets assume we want to search all the field of the table and not only the Name field. In order to do that we need to choose the records with Name LIKE $srch or Last LIKE $srch etc. The translation to MySQL query is:


$query = "select * from visitors WHERE Name LIKE '$srch' || Last LIKE '$srch' || email LIKE '$srch' || comment LIKE '$srch'";


The complete srch.php3 script top to bottom should look like:


<?
if ($search) // perform search only if a string was entered.
{
mysql_connect() or die ("Problem connecting to DataBase");
$srch="%".$search."%";
$query = "select * from visitors WHERE Name LIKE '$srch' || Last LIKE '$srch' || email LIKE '$srch' || comment LIKE '$srch'";

$result = mysql_db_query("guest_book", $query);

if (
$result)
{
echo
"Here are the results:<br><br>";
echo
"<table width=90% align=center border=1><tr>
<td align=center bgcolor=#00FFFF>Visit time and date</td>
<td align=center bgcolor=#00FFFF>User Name</td>
<td align=center bgcolor=#00FFFF>Last Name</td>
<td align=center bgcolor=#00FFFF>Email</td>
</tr>"
;

while (
$r = mysql_fetch_array($result)) { // Begin while
$ts = $r["TimeStamp"];
$name = $r["Name"];
$last = $r["Last"];
$email = $r["email"];
$comment = $r["comment"];
echo
"<tr>
<td>$ts</td>
<td>$name</td>
<td>$last</td>
<td>$email</td></tr>
<tr> <td colspan=4 bgcolor=\"#ffffa0\">$comment</td>
</tr>"
;
}
// end while
echo "</table>";
} else { echo
"problems...."; }
} else {
echo
"Search string is empty. <br> Go back and type a string to search";
}
include (
'links.x');
?>










Counting - Creating a GIF based counter using PHP and MySQL
Categories : Beginner Guides, PHP, To PHP, To MySQL, MySQL
Counting - Creating a more sophisticated GIF based counter using PHP and MySQL
Categories : Beginner Guides, MySQL, PHP, To PHP, To MySQL
Beginners guide to PHP and MySQL - Creating a simple guest book
Categories : Beginner Guides, To PHP, To MySQL, PHP, MySQL
Counting - Creating a simple counter
Categories : PHP, MySQL, Beginner Guides, To PHP, To MySQL
Jump Start to Easy URLs
Categories : PHP, Beginner Guides, MySQL, File System, To PHP
How TO Install PHP, Apache and MySQL on Linux or Unix
Categories : PHP, MySQL, Apache, Installation, Beginner Guides
Who's Linking?
Categories : PHP, Beginner Guides, To PHP
Grabb'n and Pars'n
Categories : Beginner Guides, PHP, To PHP
Start Using MySQL
Categories : MySQL, Databases, To MySQL, Beginner Guides
How To add paging (Pagination) with PHP and MySQL
Categories : PHP, Beginner Guides, Databases, MySQL, HTML and PHP
Beginners Guide to PHP - Introduction to cookies
Categories : Beginner Guides, Cookies, To PHP, PHP
Beginners guide to PHP and MySQL
Categories : PHP, Beginner Guides, Databases, MySQL, Installation
Creating an IE-Only Database Driven Menu System With PHP, MySQL and DHTML
Categories : PHP, MySQL, Databases, DHTML
PHP 101 Part 10 of 15 : A Session In The Cookie Jar
Categories : PHP, Beginner Guides, Cookies, Sessions
Case Study: Handling MySQL Growth With a PHP Class
Categories : Databases, MySQL, PHP
Anonymous wrote : 33
Every time I try to connect to MySQL database, the
following error happens:

Warning: MySQL Connection Failed: Can`t connect to
local MySQL server through
socket `/var/lib/mysql/mysql.sock` (111)
Boaz Yahav wrote : 34
Are you sure your MySQL Server is running?
Nathon Jones wrote : 46
Thanks for the good work Weberdev.com! In relation to
this simple mysql search, does anyone know how to
alter this example so that the search string can be
random keywords or phrases? Perhaps I am not
explaining this too well. Here is another example of
what I am trying to acheive: I have a database of
names. I would like my visitors to be able to search
the "name" column using a name, or surname, in any
order. If a visitor types - "Smith Paul" I would like the
results to show every record that contains
either "Smith" or "Paul" rather than only producing
results that have both "Smith Paul", in that order. So,
for example, I would get results such as "Paul
Smith", "Smith, Rogers & Sons", "David Paul Magee" etc
etc. I know it must be something to do with the
$srch="%".$search."%" section. Unfortunately this
section of code still only produces results where multi-
word phrases are an exact match! HELP ME! PLEASE!
Thank you. Nathon.
Anonymous wrote : 47
I`ve been doing something similar using the like
command.

Instead of:

$query = "select * from visitors WHERE
Name=`$search`";

I am using something more along the lines of:

$query = "select * from visitors WHERE Name like `%
$search%`";

This uses wildcards to select anything that has $search
in it.

This can also be changed to "$search%" to find
anything starting with $search or "%$seach" to find
anything ending with $search.

Since this uses wildcards it may be a little slower, but I
haven`t noticed any major speed issues on a search
through about 5000 trouble tickets.

Email me if you have any questions on this.

J. Thomas
System Admin
PSN.net
Janno Bremann wrote : 52
I`m thinking of learning php. The server is provided by a
connection provider. Can I use databases or sth over
the net without actually touching the server?
Sth like uploading or do the providers have some
database installed and can I use it. Since I practically
Know nothing all the help is welcome, thanx!
Anonymous wrote : 64
Hello! I`m a new programmer in PHP (i`m Portuguese,
and my english is not the best. OK !) and i like to now
how do you make the menus of the top page of this
page! How! If you can help me, tanks.
Obrigada...

P.S.- PHP is one of the best language to the NET in the
world!! Né...
Boaz Yahav wrote : 65
It`s simple :)

You go to :

http://www.webreference.com/dhtml/hiermenus/instructi
ons/noframes/index.html

and download the HierMenus.

berber
Anonymous wrote : 68
This script is a great example of how to search a
database but how do you limit the results to 10 per
page?
Anonymous wrote : 107
I`m new to PHP and I can`t get it to work.

Using these files, containing source code as stated in
the article:
http://www.gospelsite.net/php/links.x
http://www.gospelsite.net/php/search.php3
http://www.gospelsite.net/php/srch.php3
http://www.gospelsite.net/php/guest_book (look there)

Anyone?

Error message:

Warning: MySQL Connection Failed: Access denied for
user: `monsuur@localhost` (Using password: NO)
in /home/monsuur/www/gospelsite/php/srch.php3 on
line 4
Problem connecting to DataBase
Delphin Mutaka wrote : 116
I am a brand new self stater in this field of programming.
I please ask you to help me with some resources that can help
me be as good as you are.

What do you recommand for someone to be a good
programmer in PHP.
Thank you?
Matt wrote : 119
Where is a good place to start learning the basics of
database creation and using them in conjunction with
the web sites I develop?
Thanks
Razvan Mihailescu wrote : 120
I am new to PHP, and I am trying to learn more
about it. Does PHP only search MySql databases or
can it search something like an HTML page too?
Boaz Yahav wrote : 121
PHP doesn`t search anything. The code you write using
PHP will do what you write it to do. PHP can connect
and interact with many databases and MySQL is
probably the most popular. PHP can also read html
pages in various ways but that depends on what you
do with the code.
Zeeshan Qamar wrote : 124
Hi All

Please guide me that how to configure my win 2000
advance faimly server that it should run the php script
as I m also presently running the ASP and Cold Fusion
script on the said machine.

Thanx
Zeeshan
John King wrote : 142
This is a really nice article. I have the routine working
but when I enter a dud like "mmmmmmm" it reports
that it found something, but nothing is displayed. When
I add echo $result;, it shows Resource ID #2, which is
the same message I get for a genuine find. If I enter
nothing, the correct mesage appears and if I enter any
correct keyword, the results are displayed perfectly.
Yep, it`s got me stumped!

Can some kind person help me with this?

Regards, John
Anonymous wrote : 148
To answer almost all questions as to how this think
works:

Let`s use the search term "happy" for this example...

1) If you want to search for a the appearance of happy
in a field of your database, you should use `%happy%` --
this will search for it anywhere in each field.

2) If you want to use a longer term like "happy +
people" or "happy and people" you will have to parse
the string that is fed into the select statements and
build several different select statments based on the
way in which people have used symbols. I suggest
using +, -, not, or, and ONLY and tell people that. Then
you will take the string BEFORE IT IS FED INTO THE
SELECT STATEMENT and parse it. Then the reuslt is
controlled through a bunch of CASE or IF statements.
For example, if there is a "happy + people" you build
the select statment accordingly. This obviuosly becoems
more complicated when someone enters "happy +
people not sad not depressed - crazy" because you will
have to mke a loop search for each instance and build
the select staement through a loop. Unless someone
knows of an easier way of doing this, it is a lot of
coding, but the result should be quite impressive.

3) The Resource #ID that is returned with your $result
is because you are trying to read something that is not
an actual fields/values result. Your best bet is to throw
everything into an array (mysql_fetch_row ($result))
and then send it through a loop to make sure you get
all of the results you want.

4) You really should get some PHP books and MySQL
books. I generally do not like New Riders books, but the
DuBois MySQL book is great. PHP... wow, check the
net... I have about 4 php books. If you are good with
SAMS teach yourself series, get that to dive in. Then
read the PHP4 bible by IDG books, print out the PHP
manual (900 pages) and also the PHP developer`s
cookbook is nice.

Hope this helps...
kit roe wrote : 149
how do you make a search engine (php) with multi
input? a form that gives options..like color, shape,
texture etc. with check boxes or radio buttons.
like the form would say "choose color" and u could pick
from whatever colors were listed. same for shape and
textures. then when u click submit..a results page
would give u everything that matched what the input
was. it does search the database right?

also, u said that html pages could b searched. could u
point me to a tutorial and/or book about that?
thanks
Anonymous wrote : 153
Hi All,
I tried to use this script but I get this message all the
time:
Call to unsupported or undefined function mysql_connect
() in c:/windows/desktop/azee/srch.php3 on line 4

So could any one help me with this problem, thanks

Azee
Anonymous wrote : 171
Hi Everyone,
I have MySql installed in C:\mysql.
I created tables and imported data. Not I desparately
need a piece of VB code to write to or read from the
database. Can anyone help? I would be very grateful
as I am new to Visual Basic but not new to SQL.
Thank You!
Anonymous wrote : 178
Thank you very much for the excelent tutorial about PHP
and MySQL in the WeberDev!

Now I have PHP installed in my Windows machine, and I
can test my PHP scripts before upload it to the host.

About MySQL, I started from absolutely zero, and just
made my first database, that is working very fine.

But (many apologies for my primarysm), how can I
create my database in the real host machine?
Anonymous wrote : 206
G R E A T <<<<<
Take care of yourself.
We need you in the future.
Thanx!!!!!!!
Anonymous wrote : 214
I have been struggling to get this search script to work, and get no results from my database. I am
wondering if the table definition has something wrong with it -
mysql> describe bulletin;
+------------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+-------------+------+-----+---------+----------------+
| news_id | int(11) | | PRI | NULL | auto_increment |
| heading | varchar(48) | YES | | NULL | |
| body | text | YES | MUL | NULL | |
| date | date | YES | | NULL | |
| author_name | varchar(48) | YES | | NULL | |
| author_email | varchar(48) | YES | | NULL | |
| bulletin_number| varchar(48) | YES | | NULL | |
| bulletin_subject| varchar(64) | YES | MUL | NULL | |
| bulletin_from1 | varchar(64) | YES | | NULL | |
| bulletin_date | varchar(15) | YES | | NULL | |
| bulletin_from2 | varchar(64) | YES | | NULL | |
+------------------+-------------+------+-----+---------+----------------+
I basically copy/paste your code, only changeing the names of fields and tables to point to my database, and
when I do a search the screen just redraws with no returned data or error message.
I have a database data entry screen set up and working, and another screen where the database can be
sorted by various options. These all work fine, I just can`t get the user data input criteria (a single word) to
work with the database query string. I would like to have the search field integrated with the existing web
page, not a seperate page, so the visitor has a choice of sorting in predefined orders or of searching (the
body and subject text only).
If anyone has any suggestions please feel free to email me, I`m new at mysql and php.
daylight light wrote : 222
I am in a situation where I have 200 questions, and
each questions has its own answer. I stalled all my
answer in MySQL. I got all the connection down. But I
don`t know how to code in such a way that, when I click
at the answer Button for that question, it will function to
search for the specific answer in the database! Please
Help! urgent! for further info, pls email me at the above
email address.. Thank you
daylight light wrote : 223
Typo: I had all my connection done! Thank you
Anonymous wrote : 224
Eventually managed to get everything working. Now I
need to know how to limit number of responses and
use next/previous buttons.

Any one know ??
Anonymous wrote : 231
Look into the LIMIT command in SQL. go to
www.mysql.com and search for LIMIT
Anonymous wrote : 244
LIMIT`s Forward anf back NAV set $offset and $x>=..

$offset=15;
if (!isset($min)) $min=0;
if (!isset($max)) $max=$min+$offset;
$str = stripslashes($str);
$sql = "SELECT keywords, name, title, des, html FROM pages where keywords LIKE \"%$str%\" OR name
LIKE \"%$str%\" OR des LIKE \"%$str%\" OR title LIKE \"%$str%\" OR html LIKE \"%$str%\" ORDER BY title
DESC limit $min,$offset";
$result = @mysql_query($sql,$connection) or die("Couldn`t execute query.1");
$num = mysql_numrows($result);
$x=0;
//$msg = "Found $num Entry Matching your Query";
if ($num == 0) {$msg = "No Entries found Please try again<br>";
}
while ($row = mysql_fetch_array($result)) {
$keywords = $row[`keywords`];
$name = $row[`name`];
$title = $row[`title`];
$des = $row[`des`];
$search_result .= "<p><a
href=$url_base$name><strong>$title</strong></a><br><em>$des</em></p>";
$x++;
}
$prev=$min-$offset;
if ($prev>=0) {$prev_url = "<a href=?page=search&str=$str&min=$prev&submitted=1><-Previous
Matches</a>";}
else {$prev_url = "";}
$next=$min+$offset;
if ($x>=14) {$next_url = "<a href=?page=search&str=$str&min=$max&submitted=1>Next
Matches-></a>";}
else {$next_url = "";}
}
echo "<p>$msg</p>";
echo $search_result;
echo "<center>$prev_url $next_url</center>";
}
Alan Leahy wrote : 285
How can I limit 10 or 15 results per page?
Pascale Lunal wrote : 332
Hello,

this is a great tutorial, but...

1. how do you run a search in the entire database (not
only one table, but all the tables) ?

2. how do you run a search with multiple keywords (not
only 1 word) ?

Tutorials on the above points would be greatly
appreciated.
mu df wrote : 333
The sam e question as Pascal alrady asked?

Which PHP editor do you use? EditPlus 2 or Notepad. Or
do you prefer Dreamweaver or something of that kind?
guy dubarry wrote : 338
Hi can anyone help me. I have created a musicpage
database where a person can click on the file and
download it to their pc. I have a view script which
displays these links for downloading but when I use the
script in this article I get the info but no links to click on
to download the files. Who can help me adjust this
script to display the download links for my pipemusic
database
Steve Sims wrote : 344
When I run this I get an error message,

Warning: Failed opening `links.x` for inclusion
(include_path=``)
in /home/.sites/21/site166/web/test/srch.php on line 52

Any ideas? I have copied the links.x file as it is
highlighted on this page and put it into the same directory
as the two search pages...
Jonathen Winterburn wrote : 347
I really like the look of this script, and after much
playing am disappointed I can`t get it to work. I have
double-checked everything! Could some please have a look at
my variation and tell me if there is something obviously
wrong? The username/pwd/host/db/table/fields are all correct
(altered for this posting, of course) so there must be
something else - I keep getting the error, and I know it`s
connecting and selecting the correct db:
<?php
include("$DOCUMENT_ROOT/includes/header.php");
?>
<?php
if ($search)
{
mysql_connect(localhost,user,pass) or die ("Problem
connecting to database");
mysql_select_db(mydb) or die( "Unable to select database");
$srch="%".$search."%";
$query = "SELECT * from mytable WHERE date LIKE `$srch`
|| exhibition LIKE `$srch` || address LIKE `$srch`

|| time LIKE `$srch` || contact LIKE `$srch` || notes LIKE
`$srch`";

$result = mysql_db_query("search", $query);

if ($result)
{
echo "Exhibition Search Results:<br><br>";

while ($r = mysql_fetch_array($result)) { //
Begin while
$date = $r["date"];
$exhibition = $r["exhibition"];
$address = $r["address"];
$time = $r["time"];
$contact = $r["contact"];
$notes = $r["notes"];
echo "<table width=\"75%\" border=\"0\" cellspacing=\"0\"
cellpadding=\"3\" bordercolor=\"#000000\"

BGCOLOR=\"#FFFFFF\">";
echo "<tr>";
echo "<td class=\"exhibitdate\"><strong>$date</strong></td>";
echo "</tr>";
echo "<tr>";
echo "<td><strong>$exhibition</strong></td>";
echo "</tr>";
echo "<tr>";
echo "<td>$address</td>";
echo "</tr>";
echo "<tr>";
echo "<td><strong>Time:</strong> $time</td>";
echo "</tr>";
echo "<tr>";
echo "<td><strong>Contact:</strong> $contact</td>";
echo "</tr>";
echo "<tr>";
echo "<td>$notes</td>";
echo "</tr>";
echo "</table>";
echo "<br>";
} // end while
echo "</table>";
} else { echo "Doh!"; }
} else {
echo "Search string is empty. <br> Go back and type a
string to search";
}

?>
<?php
include("$DOCUMENT_ROOT/includes/footer.php");
?>
Jonathen Winterburn wrote : 348
It`s ok, I sorted it - I was being thick - I forgot to
specify the db within the $result = mysql_db_query("mydb",
$query) line. Doh!
niaz ahmed wrote : 368
Hi iam Niaz from india and i it`s really wonderfull work..
iam very new to this PHP please help me out.. hi friends help
me out in this PHP prgramms. thanking you all. bye mail me
Diana Browne wrote : 383
Help!
I need to lookup information from two tables.
One table has a list of keywords with ID`s.
Another table has a list of staff with a Keyword field where they
can have several ID`s in the one field (ex. 41, 23, 64)
I want to show the names of the numbers on a staff description
page (ex. press, legal, technology).

Is this possible?

Thanks.
Maria Alvarado wrote : 401
I coded with confidence after reading through this guestbook
script and related comments. I was not as lucky as others in
getting this to work for me the first time. I thought it might be a
permissions issue, so went and CHMOD to all related files. still,
i get this error:

Warning: mysql_connect() [function.mysql-connect]: Access
denied for user: 'nobody@localhost' (Using password: NO)
in /home/satxmain/public_html/srch.php3 on line 11
Problem connecting to DataBase

Is my interpretation of this error correct? There is a
function "function.mysql-connect" missing or not accessible
somehow?

Thanks for the code that encouraged me to finally try and step
beyond HTML programming.

m
vishwanath rangappanavar wrote : 400
hello i had used the same code but i am receiving a
message "search string is empty go back and enter string to
search"
Maria Alvarado wrote : 402
OK. So there is more to know about the mysql_connect() such
as that it requires 3 minor details: mysql_connect
('locahost' 'mysqluser' 'msysqlpassword' )

geez.
jez wade wrote : 405
Ok so you've just read Ton Rafi's great guide to a Simple
MySQL Search using LIKE and WHERE Clauses in a MySQL
Query, Well now I can show you how to use specific keywords
instead of exact matches in the Search String.

ie. Instead of searching for "Mr. Bigglesworth", we will
translate this string to search for "Mr." and "Bigglesworth".

This is the Theory:
User Enters Search String "Mr. Bigglesworth".
PHP Splits the string into an "Array" of "Keywords", ie. Array
("Mr.","Bigglesworth");
PHP Loops each keyword to the MySQL DB and submits a
SEPERATE MySQL Query for each Keyword.
PHP Puts All This Together and Outputs via Echo.

Ok lets get Coding:

===============================

Remember these lines:
$query = "select * from visitors WHERE Name='$search'";
$result = mysql_db_query("guest_book", $query);
while ($r = mysql_fetch_array($result)) { // Begin while
$ts = $r["TimeStamp"];
$name = $r["Name"];
$last = $r["Last"];
$email = $r["email"];
$comment = $r["comment"];
echo "<tr>
<td>$ts</td>
<td>$name</td>
<td>$last</td>
<td>$email</td></tr>
<tr> <td colspan=4 bgcolor=\"#ffffa0\">$comment</td>
</tr>";
} // end while

===============================

We will modify this to:
$search = explode(" ",$search); // Explode a string into an
array, Split string by Spaces (to form Keywords).
foreach($search As $keyword) // foreach loops through
each Array Item and sets the item to "$keyword"
{
$keyword2 = "%".$keyword."%";
$query = "select * from visitors
WHERE Name LIKE '$keyword' ||
Last LIKE '$keyword' ||
email LIKE '$keyword' ||
comment LIKE '$keyword'
";
$result = mysql_db_query("guest_book", $query); //
Submits Query for each Keyword

while ($r = mysql_fetch_array($result)) { // Begin while
$ts = $r["TimeStamp"];
$name = $r["Name"];
$last = $r["Last"];
$email = $r["email"];
$comment = $r["comment"];
// Notice the 'Output' Variable has a . (dot) in front of =
(equals), this ADDS to any variable named "Output"
$Output .= "<tr>
<td>$ts</td>
<td>$name</td>
<td>$last</td>
<td>$email</td></tr>
<tr> <td colspan=4 bgcolor=\"#ffffa0\">$comment</td>
</tr>";
} // end while
}
echo($Output);


That should be it. REMEMBER: The More Keywords the More
MySQL Queries = More Resources = Slower Script.
I'm sure there are more ways for this. but this is simple and
easy to understand.
jez wade wrote : 406
vishwanath rangappanavar -
Remember some PHP installations do NOT use Global Vars EG:
instead of using $formField to get a form field you must use
$_POST['formField'] instead.


Maria Alvarado -
That error means you have not connected with the correct
user information, usually default mysql installations have a
username with no password, ie: mysql_connect
("localhost","root",""); - should connect to a default mysql
installation.

Steve Sims -
The include should work, the error is stating that you have not
given a string for the include function. make sure your syntax
is correct, ie: Include("links.x"); or try Include_Once("links.x"); .

Pascale Lunal -
For Multiple Tables you need Multiple Queries, you would use
an array of all the table names, and loop the query and result
code using foreach().
For multiple keywords look at the above comment.

Leahy Alan -
To LIMIT Results from any query just add "LIMIT 0,15" where 0
is minimum and 15 is maximum rows to be returned. this is
PER query and will not work with the above comment for
multiple keywords. for above just add this at the start of the
FOR loop:
if($Total_Results => 15){ Break; }else{ $Total_Results++; }

Call to unsupported or undefined function mysql_connect
() in c:/windows/desktop/azee/srch.php3 on line 4
-
This error means that the MYSQL Library for PHP has not been
installed/Enabled, this is common for new PHP installations.
Just find your php.ini and search for "extension=mysql.dll" or
similar and delete the ; and the start of the line. If no luck
search google for downloading and installing the php/mysql
extension for your version of PHP.

John King -
To quickly test if you have the result you wanted without
looping the resut, just using Print_r($Result); or var_dump
($Result); and open the page in notepad, this will give you a
visual accurate representation of any array.

Warning: MySQL Connection Failed: Can`t connect to
local MySQL server through
socket `/var/lib/mysql/mysql.sock` (111)
-
mysqld.exe is not running, press CTRL+ALT+DEL and click
the "Proceses" tab, if this exe is not listed go to Start->Run and
type "Services.msc", look for a service called MySQL or
MySQL5 or similar, Right Click and select Properties, Try
Starting the service, if it does not start or starts then stops i
suggest reinstalling mysql using a step-by-step tutorial.


------
To Learn more php/mysql i STRONGLY suggest looking for
some PDF Books online (some Free) or go to a book store and
buy one, i learned using code snippets from hotscripts(dot)
com and a book called EasyPHP from the Easy Series of
programming books. it really is Easy.

Thanks,
[email protected]

If you have a query about this or any of my comments please
use the subject "Weberdev Comment" in your emails and ill try
to get back to you asap. thanks.
Dev Wray wrote : 410
when I try search I get

Search string is empty.
Go back and type a string to search even tho I have a valid search string

If I try to add a new entry I get
No UserName Entered. Please go back and reenter UserName
even tho I have clearly filled in this box

I pretty much copied and pasted everything and created the database

is there a step I might have missed?

I've tried a couple examples tiring to get a php sql query to work but none have been successful