Jump to content
xisto Community
Sign in to follow this  
bigfatme2000

Searching With Php And Mysql The easy way :P

Recommended Posts

Searching with PHP and MySQL is pretty easy when you think about it, especially if you're doing it the simple way (without boolean or whatever) :ph34r:

 

It consists of a few forms, a query and an output. As I said, simple!

 

<form name=\"form1\" id=\"form1\" method=\"post\" action=\"<? $php_self ?>\"><table width=\"100%\" border=\"0\" cellspacing=\"1\" cellpadding=\"2\"><tr><td style=\"text-align: center;\"><input name=\"search\" type=\"text\" id=\"search\" /></td></tr><tr><td style=\"text-align: center;\"><input name=\"submit\" type=\"submit\" id=\"submit\" value=\"Search!\" /></td></tr></table></form>

The form that you just made contains a text input that people will type into, the next code will extract the form data and then search it..

 

Form processing :P

 

 

$search = htmlspecialchars(addslashes($_POST[\\\'search\\\']), ENT_QUOTES); if(isset($_POST[\\\'submit\\\'])) { if(!$search) { echo \\\"No search entered, please go back and fill in the fields properly.\\\"; } else { $query = mysql_query(\\\"SELECT * FROM table WHERE field LIKE \\\'%$search%\\\'\\\"); $resultnum = mysql_num_rows($query); // Just print $resultnum if you want to show how many results returned if($resultnum>0) { // Echos out matches if anything was found while($row=mysql_fetch_array($query)) { // Starts spitting out the data echo \\\"You can put a link to the result article here, or something else. This is what\\\'ll show up when a user gets a result, for each result.<br />\\\" } } } } else { echo \\\"<p>No search entered?</p>\\\"; }

And that's it. Let me just break this down for you :blink:

htmlspecialchars(addslashes:

This line does two things; it cleans out any chance of an SQL injection to your database, and then it adds slashes to the value which makes the search more accurate. If you don't add slashes, then if you searched for cheese, it would return anything with a c, h, e or s in your database. So much for search relavance, eh? :P

 

$query = mysql_query(\\\"SELECT * FROM table WHERE field LIKE \\\'%$search%\\\'\\\"):

This is the query that does the search. Notice the percentage signs in the LIKE part - don't forget these. They work as wildcards.

 

And the rest I'm sure you'll understand. :):P

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.