I am trying to collect info from four separate text fields and generate queries in the backend to display the results. I have tried many solutions already suggested on here but I keep getting duplicate results.
I have it working with one query:
<?php
$query = "SELECT * FROM book WHERE booktitle LIKE '%" . mysql_real_escape_string($_POST['title']) . "%'";
$result = mysqli_query($con, $query) or die("Error in query");
while ($row = mysqli_fetch_array($result)) {
?>
<img src="<?php echo $row[12]; ?>" width="112px" height="150px" />
<?php
echo "<b>Title: </b>" . $row[1] . "<br />";
echo "<b>Author: </b>" . $row[2] . "<br />";
echo "<b>Price:</b> £" . $row[9] . "<br />";
echo "<b>Description:</b> " . substr($row[3],0,320) . "...<br /><hr>";
}
But I also need to incorporate results from the other 3 somehow??
$query = "SELECT * FROM book WHERE author LIKE '%" . mysql_real_escape_string($_POST['author']) . "%'";
$query = "SELECT * FROM book WHERE isbn LIKE '%" . mysql_real_escape_string($_POST['isbn']) . "%'";
$query = "SELECT * FROM book WHERE description LIKE '%" . mysql_real_escape_string($_POST['keyword']) . "%'";
Any help would be greatly appreciated. Thanks in advance.
You can use an OR statement with the LIKE keyword to search all of these at the same time.
$query = "SELECT * FROM book WHERE booktitle LIKE '%" . $title . "%' OR author LIKE'%" . $author . "%' OR isbn LIKE '%" . $isbn . "%' OR description LIKE '%" . $keyword . "%';
If the variables are empty then you will have WHERE booktitle LIKE '%%', which returns all rows. You will need to build the query based on the input.
// Determine the WHEREs to use
$where = array();
if ( ! empty($title))
$where[] = "booktitle LIKE '%" . $title . "%'";
if ( ! empty($author))
$where[] = "author LIKE '%" . $author . "%'";
if ( ! empty($isbn))
$where[] = "isbn LIKE '%" . $isbn . "%'";
if ( ! empty($description))
$where[] = "description LIKE '%" . $description . "%'";
// Build the query
$query = 'SELECT * FROM book';
if ( ! empty($where))
$query .= ' WHERE ' . implode(' OR ', $where);
Note: I have omitted escaping the input for readability.
<?php
$mysqli = new mysqli("localhost", "username", "password", "database_name");
$book_title = mysql_real_escape_string($_POST['title']);
$author = mysql_real_escape_string($_POST['author']);
$isbn = mysql_real_escape_string($_POST['isbn']);
$keyword = mysql_real_escape_string($_POST['keyword']);
$query = "SELECT * FROM book WHERE booktitle LIKE '%{$book_title}' OR author LIKE'%" . $author . "%'
OR isbn LIKE '%" . $isbn . "%' OR description LIKE '%" . $keyword . "%'";
$result = $mysqli->query($query);
while($row = $result->fetch_array()):?>
<img src="<?=$row['image_column_name']; ?>" width="112px" height="150px" />
<b>Title:</b> <?=$row['title_column_name']; ?> <br>
<b>Author:</b> <?=$row['author_column_name']; ?> <br>
<b>Price:</b> <?=$row['price_column_name']; ?> <br>
<b>Description:</b> <?=substr($row['desc_column_name'],0,320)?>
<hr>
<?php endwhile; ?>
Related
I am trying to get the result from the database with the mysql LIKE but in wordpress its not working here is the code of what i am trying
//this is what i am putting in where clause.
$state = $_POST['state'];
//table name.
$table_name = $wpdb->prefix . 'userprofile';
//trying but this is returning empty
$q = 'SELECT * FROM ' . $table_name . 'WHERE state LIKE \'%' . esc_sql( like_escape( $state ) ) . '%\'';
echo $q;
$result = $wpdb->get_results($q);
if (empty($result)) {
echo "the result is empty";
}
//returns empty array.
print_r($result);
You are missing a space:
$q = 'SELECT * FROM ' . $table_name . 'WHERE[..snip..]
^---here
which means you're producing
SELECT * FROM whateveruserprofileWHERE
which is invalid SQL.
Like Marc B. said, there are some missing quotes and unnecessary quotations.. change your query line, to this:
$q = "SELECT * FROM $table_name
WHERE state LIKE '%". esc_sql( like_escape( $state ) ) . "%'
AND WHERE city LIKE '%". esc_sql( like_escape( $city ) ) . "%'
AND WHERE session LIKE '%". esc_sql( like_escape( $session ) ) . "%'
OR WHERE another LIKE '%". esc_sql( like_escape( $another ) ) . "%' ";
and your POST line to this:
$state = $_POST['state'];
do this way
$state = esc_sql( $state );
$state = like_escape( $state );
$state = '%' . $state . '%';
$q = 'SELECT * FROM ' . $table_name . 'WHERE state LIKE '$state';
I am having a problem getting a query to work (and also am questioning the security of the query).
if(isset($_POST)){
$sql = "SELECT * FROM members WHERE";
if($_POST['FirstName_S'] !== ''){
$sql .= " FirstName LIKE '%" . $_POST['FirstName_S'] . "%'";
}
if($_POST['LastName_S'] !== ''){
$sql .= " OR LastName LIKE '%" . $_POST['LastName_S'] . "%'";
}
if($_POST['Firm_S'] !== ''){
$sql .= " OR Firm LIKE '%" . $_POST['Firm_S'] . "%'";
}
if($_POST['Country_S'] !== ''){
$sql .= " OR Country LIKE '%" . $_POST['Country_S'] . "%'";
}
if($_POST['City_S'] !== ''){
$sql .= " OR City LIKE '%" . $_POST['City_S'] . "%'";
}
if($_POST['State_S'] !== '' AND $_POST['State_S'] !== 'other'){
$sql .= " OR State LIKE '%" . $_POST['State_S'] . "%'";
}
}
Obviously, if FirstName_S is undefined, the query breaks saying "WHERE OR". It seems like it would have a logical fix, but I've been staring at it for a little too long.
Also, sql injection was brought up as a concern, and as a side-question, would sanitizing the input be enough? Or is this altogether bad practice?
if(isset($_POST)){
$sql = "SELECT * FROM members WHERE";
if($_POST['FirstName_S'] !== ''){
$sql .= "OR FirstName LIKE '%" . $_POST['FirstName_S'] . "%'";
}
if($_POST['LastName_S'] !== ''){
$sql .= " OR LastName LIKE '%" . $_POST['LastName_S'] . "%'";
}
if($_POST['Firm_S'] !== ''){
$sql .= " OR Firm LIKE '%" . $_POST['Firm_S'] . "%'";
}
if($_POST['Country_S'] !== ''){
$sql .= " OR Country LIKE '%" . $_POST['Country_S'] . "%'";
}
if($_POST['City_S'] !== ''){
$sql .= " OR City LIKE '%" . $_POST['City_S'] . "%'";
}
if($_POST['State_S'] !== '' AND $_POST['State_S'] !== 'other'){
$sql .= " OR State LIKE '%" . $_POST['State_S'] . "%'";
}
$sql=str_replace("WHERE OR","WHERE",$sql); // quick dirty fix
}
Ofcourse you'd need to sanitize the input, but since you didn't mention which MySQL API you use, I did not add any sanitization functions yet. You can look at http://php.net/mysqli_real_escape_string
do it other way as follow
if(isset($_POST)){
$sql = "SELECT * FROM members WHERE";
if($_POST['FirstName_S'] !== ''){
$sql_arr[]=" FirstName LIKE '%" . $_POST['FirstName_S'] . "%'";
}
if($_POST['LastName_S'] !== ''){
$sql_arr[]= " LastName LIKE '%" . $_POST['LastName_S'] . "%'";
}
if($_POST['Firm_S'] !== ''){
$sql_arr[]= " Firm LIKE '%" . $_POST['Firm_S'] . "%'";
}
if($_POST['Country_S'] !== ''){
$sql_arr[]= " Country LIKE '%" . $_POST['Country_S'] . "%'";
}
if($_POST['City_S'] !== ''){
$sql_arr[]= " City LIKE '%" . $_POST['City_S'] . "%'";
}
if($_POST['State_S'] !== '' AND $_POST['State_S'] !== 'other'){
$sql_arr[]= " State LIKE '%" . $_POST['State_S'] . "%'";
}
if(!empty($sql_arr)){
$sql.=implode(' OR ',$sql_arr);
}
}
The quick fix is to add 1=1 to your query, so your query ends with WHERE 1=1. That allows you to be free to append any number of OR something to your query, without being concerned with omitting the OR on the first one.
(That 1=1 predicate doesn't cause any problem; that will be evaluated at parse time, and doesn't appear in the execution plan.)
As to SQL Injection, yes, this code is susceptible. If you are using mysql interface, then sanitize the post variables with mysql_real_escape_string function. If you are using mysqli or PDO (and you should be), then use parameterized queries.
$stmt = $dbConnection->prepare('SELECT * FROM members WHERE FirstName LIKE ? OR LastName LIKE ? OR FIRM LIKE ? OR Country LIKE ? OR CITY LIKE ? OR STATE LIKE ?');
if($_POST['FirstName_S'] !== ''){
$stmt->bind_param('FirstName', '%'.$_POST['FirstName_S'].'%');
} else {
$stmt->bind_param('FirstName', '%');
}
… // do this for all your parameters
$stmt->execute();
I think this could help you:
if(isset($_POST)){
$sql = "SELECT * FROM members";
if($_POST['FirstName_S'] !== ''){
$sql .= " WHERE FirstName LIKE '%" . $_POST['FirstName_S'] . "%'";
}
else {
$sql .= " WHERE FirstName LIKE '%'";
}
if($_POST['LastName_S'] !== ''){
$sql .= " OR LastName LIKE '%" . $_POST['LastName_S'] . "%'";
}
if($_POST['Firm_S'] !== ''){
$sql .= " OR Firm LIKE '%" . $_POST['Firm_S'] . "%'";
}
if($_POST['Country_S'] !== ''){
$sql .= " OR Country LIKE '%" . $_POST['Country_S'] . "%'";
}
if($_POST['City_S'] !== ''){
$sql .= " OR City LIKE '%" . $_POST['City_S'] . "%'";
}
if($_POST['State_S'] !== '' AND $_POST['State_S'] !== 'other'){
$sql .= " OR State LIKE '%" . $_POST['State_S'] . "%'";
}
}
and for the SQL injections, you can check General_Twyckenham comment.
You could compose the WHERE command based on what parameters is entered...
if(isset($_POST)){
$sql_where = '';
$sql = "SELECT * FROM members ";
if($_POST['FirstName_S'] !== ''){
$sql_where .= (($sql_where != '')?('OR '):(''))." FirstName LIKE '%" . $_POST['FirstName_S'] . "%' ";
}
if($_POST['LastName_S'] !== ''){
$sql_where .= (($sql_where != '')?('OR '):(''))." LastName LIKE '%" . $_POST['LastName_S'] . "%' ";
}
if($_POST['Firm_S'] !== ''){
$sql_where .= (($sql_where != '')?('OR '):(''))." Firm LIKE '%" . $_POST['Firm_S'] . "%' ";
}
if($_POST['Country_S'] !== ''){
$sql_where .= (($sql_where != '')?('OR '):(''))." Country LIKE '%" . $_POST['Country_S'] . "%' ";
}
if($_POST['City_S'] !== ''){
$sql_where .= (($sql_where != '')?('OR '):(''))." City LIKE '%" . $_POST['City_S'] . "%' ";
}
if($_POST['State_S'] !== '' AND $_POST['State_S'] !== 'other'){
$sql_where .= (($sql_where != '')?('OR '):(''))." State LIKE '%" . $_POST['State_S'] . "%' ";
}
$sql .= (($sql_where != '')?('WHERE '.sql_where):(''));
}
I am trying to make an advanced search engine, one in which you can search by first name, last name, zip, city, state, phone, cell phone and email.
I have managed to get it to search by first name, but you have to type the first name correctly as with anything else, I took out everything else but the first name search to find my problem yet, I have yet to find it, Here is a MySQL version of my search code that I am trying to convert to PDO.
MySQL:
<?php
//This is only displayed if they have submitted the form
if ($searching =="yes") {
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
if ($f == "")
if ($info == "")
if ($zip == "")
if ($state == "")
if ($email == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("xxx", "xxxx", "xxx") or die(mysql_error());
mysql_select_db("xxxx") or die(mysql_error());
// We preform a bit of filtering
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM users WHERE fname
LIKE '%" . mysql_real_escape_string($find) . "%' AND lname
LIKE '%" . mysql_real_escape_string($f) . "%' AND info
LIKE '%" . mysql_real_escape_string($info) . "%' AND zip
LIKE '%" . mysql_real_escape_string($zip) . "%' AND state
LIKE '%" . mysql_real_escape_string($state) . "%' AND email
LIKE '%" . mysql_real_escape_string($city) . "%' AND city
LIKE '%" . mysql_real_escape_string($email) . "%'");
?>
<?php
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo "<hr><br>First Name: ";
echo $result['fname'];
echo "<br>Last Name: ";
echo $result['lname'];
echo "<br>Home Phone: ";
echo $result['info'];
echo "<br>Cell Phone: ";
echo $result['cp'];
echo "<br>City: ";
echo $result['city'];
echo "<br>State: ";
echo $result['state'];
echo "<br>Zip: ";
echo $result['zip'];
echo "<br>Email: ";
echo $result['email'];
echo "<br><hr>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:
</b> " .$find;
}
?>
Now here is my PDO version:
<?
$dsn = 'mysql:host=xxx;dbname=xxx;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'xxx','xxx', $opt);
$stmt = $pdo->prepare("SELECT * FROM users WHERE fname= ?");
if ($stmt->execute(array($fname)));
while ($row = $stmt->fetch()) {
print $row['fname'] . "<br>";
print $row['lname'] . "\t<br>";
print $row['info'] . "\n<br>";
print $row['cp'] . "\n<br>";
print $row['state'] . "\n<br>";
print $row['city'] . "\n<br>";
print $row['zip'] . "\n<br>";
print $row['email'] . "\n<br>";
}
?>
Tips, advice, and comments are welcome and appreciated.
I guess you would build a sql-string and use parameters.
You would not include into your sql fields that the user left empty.
// **EDIT** check if there's any user-input...
if (!isset($_POST['fname']) && !isset($_POST['lname'])) { // add all your input-fields
echo "<p>please enter a search term!</p>";
echo 'try again";
exit();
}
$sql = '';
$bind = array();
if (strlen($_POST[‘firstname‘]) > 0) { // assuming your form-method is "post"
$sql .= 'AND fname LIKE :fname ';
$bind['fname'] = '%'.$_POST['firstname'].'%';
}
if (strlen($_POST['lastname']) > 0)
$sql .= 'AND lname LIKE :lname ';
$bind['lname'] = '%'.$_POST['lastname'].'%';
}
// ...
// do this will all of your input-fields...
$sql = 'SELECT * FROM users WHERE ' . trim($sql, 'AND') . ' ORDER BY lname';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($bind));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// go ahead and display your results with foreach...
Your biggest problem is you’re using AND instead of OR in your WHERE clause. Change it to this:
SELECT *
FROM `table`
WHERE `name` LIKE '%string%'
OR `zip` LIKE '%string%'
// AND SO ON
I originally had this working:
url: http://server/blah.php?FacilityCode=FT
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
$result = mysql_query($sql);
But I want to change this so that people can submit multiple values in the query strying somehow, ie: http://server/blah.php?FacilityCode=FT,CC,DD,EE
I tried changing the query to an "IN" clause instead of an "equals" but I'm not sure how to get the ' marks around each element.
Use implode() function for IN (...).
$a = array('AB', 'CD', 'EF', 'ZE');
echo "field IN ('" . implode("', '", $a) . "')";
... will output:
field IN ('AB', 'CD', 'EF', 'ZE')
+escape every option you get.
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$array=explode(',',$facilitycode);
foreach ($array as $a){$output.="'$a',";}
$clause=substr($output,0,-1);
If your trying to create a string which looks like this: 'AB', 'CD', 'EF', 'ZE'
Try this before its placed inside the query:
$facilitycode = preg_replace('/([^,]+)/', '\'$1\'', $facilitycode);
I wrote this based on your query, but still I dont get this part of query "AND ('" . $facilitycode . "' = ''", anyway you need to check if $_GET data have "," and if does explode that variable by "," so that you can add an OR clausule for everything that was separated by "," in $_GET data.
After that just form your query by doing a foreach for every element in exploded array like I done below:
<?php
$facilitycode = $_GET["FacilityCode"];
$facility_number_chk = strpos($facilitycode, ",");
if ($facility_number_chk > -1) {
$facilitycode = explode(",", $facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = ''";
foreach($facilitycode as $facode) {
$facode = mysql_real_escape_string($facode);
$sql .= " OR Facility.FacilityCode = '". $facode . "'";
}
$sql .= "')";
}
else {
$facilitycode = mysql_real_escape_string($facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
}
$result = mysql_query($sql);
And if there is only one element in $_GET data just do an else like I done with your regular query.
I ended up using a combination of a few of the answers. Basically I exploded on the ",", then did a foreach to add the ' marks and call escape_string, and then imploded it back.
$facilitycodes = $_GET["FacilityCode"];
if ($facilitycodes == '') {
$additionalfilter = '';
}
else {
$facilitycodearray = explode(",", $facilitycodes);
foreach($facilitycodearray as &$facilitycode) {
$facilitycode = "'" . mysql_real_escape_string($facilitycode) . "'";
}
$facilitycodesformatted = implode(",", $facilitycodearray);
$additionalfilter = " AND Facility.FacilityCode IN (" . $facilitycodesformatted . ")";
}
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
$additionalfilter;
<form method="post" action="oabtest.php?go" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
<p>A | B | C |D |E |F |G |H |I |J |K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z </p>
<p>You may also search by Patrol.</p>
<form method="post" action="oabtest.php?go" id="searchform">
<input type="text" name="patrol">
<input type="submit" name="submit" value="Search">
</form>
<?php
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect("localhost", "*****", "*****");
if (!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db("troop97_***");
if (!$db) {
die("Unable to select database");
}
if (isset($_POST['submit'])) {
if (isset($_GET['go'])) {
if (preg_match("/[A-Z | a-z]+/", $_POST['name'])) {
$name = $_POST['name'];
//-query the database table
$sql = "SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '" . mysql_real_escape_string($name) . "%' OR Last_Name LIKE '" . mysql_real_escape_string($name) . "%'";
//-run the query against the mysql query function
$result = mysql_query($sql);
//-count results
$numrows = mysql_num_rows($result);
echo "<p>" . $numrows . " results found for " . stripslashes($name) . "</p>";
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$ID = $row['ID'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" . $First_Name . " " . $Last_Name . "</li>\n";
echo "</ul>";
}
} else {
echo "<p>Please enter a search query</p>";
}
}
}
if (isset($_GET['by'])) {
$letter = $_GET['by'];
//-query the database table
$letter = mysql_real_escape_string($letter);
$sql = "SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '" . $letter . "%'
OR Last_Name LIKE '" . $letter . "%'";
//-run the query against the mysql query function
$result = mysql_query($sql);
//-count results
$numrows = mysql_num_rows($result);
echo "<p>" . $numrows . " results found for " . $letter . "</p>";
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$ID = $row['ID'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" . $First_Name . " " . $Last_Name . "</li>\n";
echo "</ul>";
}
}
if (isset($_POST['submit'])) {
if (isset($_GET['go'])) {
if (preg_match("/[A-Z | a-z]+/", $_POST['patrol'])) {
$patrol = $_POST['patrol'];
//-query the database table
$patrol = mysql_real_escape_string($patrol);
$sql = "SELECT ID, First_Name, Last_Name FROM contact WHERE Patrol LIKE '" . mysql_real_escape_string($patrol) . "%'";
//-run the query against the mysql query function
$result = mysql_query($sql);
//-count results
$numrows = mysql_num_rows($result);
echo "<p>" . $numrows . " results found for " . $patrol . "</p>";
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$ID = $row['ID'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" . $First_Name . " " . $Last_Name . "</li>\n";
echo "</ul>";
}
}
if (isset($_GET['id'])) {
$contactid = $_GET['id'];
//-query the database table
$sql = "SELECT * FROM contact WHERE ID=" . $contactid;
//-run the query against the mysql query function
$result = mysql_query($sql);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$First_Name = $row['First_Name'];
$Last_Name = $row['Last_Name'];
$Home_Phone = $row['Home_Phone'];
$Cell_Phone = $row['Cell_Phone'];
$Work_Phone = $row['Work_Phone'];
$Email = $row['Email'];
$Home_Street = $row['Home_Street'];
$Home_City = $row['Home_City'];
$Home_State = $row['Home_State'];
$Home_Zip = $row['Home_Zip'];
$Troop_Role = $row['Troop_Role'];
$Patrol = $row['Patrol'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . $First_Name . " " . $Last_Name . "</li>\n";
echo (empty($Home_Phone)) ? '' : "<li>" . $Home_Phone . " Home</li>\n";
echo (empty($Cell_Phone)) ? '' : "<li>" . $Cell_Phone . " Cell</li>\n";
echo (empty($Work_Phone)) ? '' : "<li>" . $Work_Phone . " Work</li>\n";
echo "<li>" . "" . $Email . "</li>\n";
echo "<li>" . $Home_Street . "</li>\n";
echo "<li>" . $Home_City . ", " . $Home_State . " " . $Home_Zip . "</li>\n";
echo "<li>" . $Troop_Role . "</li>\n";
echo "<li>" . $Patrol . "</li>\n";
echo "</ul>";
}
}
}
}
SQL Injection Risk
If you ever use a value from a submitted form when interacting with a database, you should escape the content before doing so. In MySQL, the best function to do this is mysql_real_escape_string() PHP Manual
$sql="SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '" . mysql_real_escape_string( $name ) . "%' OR Last_Name LIKE '" . mysql_real_escape_string( $name ) ."%'";
Adding Fields to Search
If you are wanting to add an additional field, like "Department" to the search query, you simply have a field on the search form corresponding to it, and then adapt your SQL Search to have it included in the WHERE clause:
$sql="SELECT ID, First_Name, Last_Name
FROM contact
WHERE ( First_Name LIKE '" . mysql_real_escape_string( $name ) . "%'
OR Last_Name LIKE '" . mysql_real_escape_string( $name ) ."%' )
AND Department='" . mysql_real_escape_string( $department ) ."'";
Using One Field for Two Searches
If you wanted to use a single text field to perform the above search, you will need to decide on some kind of prefix for users to prefix the value for the second field with.
For instance, if we specify "in:" as a prefix to designate the Department, so a search for "John in:Radiology" would look for any person with a first, or last, name starting with "John" but only those in the "Radiology" department.
list( $name , $department ) = explode( ' in:' , $_POST['name'] , 2 );
instead of
$name = $_POST['name'];
LIKE Search Limitation
At the moment, your code will only search for First Names and/or Last Names which start with the entered value. You can make the search return either fields which simply contain (not just start with) the entered value by putting another "%" at the start of the search string:
$sql="SELECT ID, First_Name, Last_Name FROM contact WHERE First_Name LIKE '%" . $name . "%' OR Last_Name LIKE '%" . $name ."%'";
Full-Text Search
You may want to look at this tutorial - Using MySQL Full-text Searching. It covers the concepts of Full-Text Searching, will allows you to find one, or more, words submitted through a single field across multiple database fields.
Limit Returned Rows
Always a good idea to limit the number of rows you return for a search, whether you paginate or simply show X rows. Failing to do this would allow a malicious user to essentially scrape your whole database by simple searching for each letter of the alphabet.
Add your hypothetical field say search_field and then search for it with "SELECT * FROM contact WHERE search_field='search value' order by First_Name", don't forget to index on search_field if it is going to be a unique field like email. I hope the code you pasted above will not go into production. Do not trust user inputs and filter them properly before you used them in SQL queries, needless to say store db credentials and connection string in a separate file and include it.