Searching multiple values - php

So far i have created a search box, which searches the primary key of my database.
How can i modify my php query to search multiple values in my database.
eg: If i search the name of the car instead of the VIN (primary key) it will show all the results matching the search value.
This
$query = ("SELECT * FROM cars
WHERE VIN='$VIN'");
This is my form :
<form name="search" action="http://www.deakin.edu.au/~sjrem/SIT104_3/cars.php" method="post">
<h2> Search for a car of your choice </h2>
<table border="0">
<tr>
<td><input type="text" name="VIN" /> </td>
</tr>
</table>
<p>
<input type="submit" name="action" value="search" />
</FORM>

Have you tried something like $query = ("SELECT * FROM cars WHERE VIN='$VIN' OR name LIKE '%$VIN%'");?
"LIKE" uses % as wildcard, so it will find all cars that have $VIN in their name.
But anyway make sure to mysql_real_escape_string() your parameter $VIN first, to prevent SQL injections!

Use the following query:
$query = ("SELECT * FROM cars WHERE Name LIKE '%$txtName%'");
NOTE:: Wildcard % is been used at the beginning and end to return all names having your search word anywhere in the field.

something like this might work for you
$query = ("SELECT * FROM cars WHERE VIN='$VIN' OR CARS='$VIN'");

Related

MySQL query updating depending on $_POST values

I am having trouble thinking out a good way to update my query depending on user $_POST values. Basically I have user management search button, where site administrator can search for his sites users. In my example:
<div id="website_user_management_search_left">
<div id="website_user_management_search_left_leftside">
<p>Name:</p>
<p>Surname:</p>
<p>Telephone:</p>
<p>Group:</p>
<p>Discount group:</p>
</div>
<div id="website_user_management_search_left_rightside">
<input type="text" name="#" value="#" id="userSearch_name">
<input type="text" name="#" value="#" id="userSearch_surname">
<input type="text" name="#" value="#">
<input type="text" name="#" value="#">
<input type="text" name="#" value="#">
<input type="submit" id="button_adminUserSearch" value="Search">
</div>
Then after pressing "Search" button AJAX sends request to retrieve results, but how can I handle this dynamic query?
For example - if user just presses "Search" query would look like:
mysqli_query($dbconnect,"SELECT * FROM accounts");
For example - if user specifys $_POST["name"] value, query would look like:
mysqli_query($dbconnect,"SELECT * FROM accounts WHERE name='".$_POST["name"]."'");
Problem is - how can I efficiently handle this kind of query? It would be dumb to check which values is "isSet" and then make tons of query cases.
I hope you understood my problem and can help out with it, because it`s kinda hard to explain it.
Maybe you're looking for something like it :
if(empty($_POST['name'])) {
$name = null;
} else $name = $_POST['name'];
Then in your statement, your condition would be :
WHERE (name=:name OR :name is null)
If name isset, it will search for this name, else it will return true and query will not be affected
You could do something like that:
mysqli_query($dbconnect,"SELECT * FROM accounts WHERE name LIKE'%".$_POST["name"]."%'");
But there are two little problems:
You don't have escaped your user input data with mysqli_escape_string() and:
You shouldn't do that. A better way would be to add a where clause only, if name POST data is set:
$where = '';
if ($_POST['name']) {
$where = ' WHERE name = '".$name."'"';
}
mysqli_query($dbconnect,"SELECT * FROM accounts" . $where);

MySQL/PHP: connecting two individual search forms

My situation:
I have two different forms. One common search form where users can search for products by their name/description, and another form that lets users search for products by their location (postcode and city).
This is the html for my search form:
<form name="searchform" method="post" action="index.php?go" class="searchform">
<input type="text" name="search" value="" placeholder="Suchen..." class="field_search" id="tags">
</form>
and this is the html for my location-search form:
<form class="location" method="post" action="index.php?go_location">
<input type="image" src="img/location/location.png" width="30" height="30" id="location_image" title="Ortung aktivieren"/>
<input type="text" size="18" placeholder="PLZ, Ort" name="location" id="location" title="Standort angeben"/>
<input type="image" name="" value="" src="img/location/go.png" width="30" height="30" id="location_submit"/>
</form>
and the corresponding php:
if(isset($_POST['search'])){
if(isset($_GET['go'])){
if(preg_match("/[A-Z | a-z]+/", $_POST['search'])){
$input=$_POST['search'];
$currently_searching = true;
//connect to db
$sql="SELECT * FROM table WHERE Name LIKE '%".$input."%' OR Description LIKE '%".$input."%'";
//echo results
}}}}
elseif(isset($_POST['location'])){
if(isset($_GET['go_location'])){
$input_location=$_POST['location'];
$currently_locationing = true;
$sql="SELECT * FROM table WHERE Postcode LIKE '%".$input_location."%' OR City LIKE '%".$input_location."%' OR Combined LIKE '%".$input_location."%' OR Combined2 LIKE '%".$input_location."%'";
//echo results
}}}
Now, individually, they work fine.
What I would like to achieve is connecting these two forms in a way that lets users who are already searching for a certain string (via the common search form) use the location - search form to narrow the results down to those corresponding with the given postcode...
I hope this is clear. I thought something like: If a user uses the common search form, the
$currently_searching
variable becomes "true", so if this variable is true and the user is using the location - search form, then connect them... so I tried adding something like this to the php-statement:
elseif(isset($_POST['location']) && $currently_searching == true){
if(isset($_GET['go_location']) && $currently_searching == true){
if($currently_searching == true){
$input_location=$_POST['location'];
$currently_locationing = true;
//connect to db
$sql="SELECT * FROM table WHERE (Name LIKE '%".$input."%' OR Description LIKE '%".$input."%') AND (Postcode LIKE '%".$input_location."%' OR City LIKE '%".$input_location."%' OR Combined LIKE '%".$input_location."%' OR Combined2 LIKE '%".$input_location."%')";
//echo results
}}}}
It doesn't work though. I'd appreciate some help guys! Thanks in advance.
Here is a little trick. Add the id locationForm to your location form and searchForm to your search form, so it looks like this:
<form id="locationForm" class="location" method="post" action="index.php?go">
<input type="image" src="img/location/location.png" width="30" height="30" id="location_image" title="Ortung aktivieren"/>
<input type="text" size="18" placeholder="PLZ, Ort" name="location" id="location" title="Standort angeben"/>
<input type="image" name="" value="" src="img/location/go.png" width="30" height="30" id="location_submit"/>
</form>
<form id="searchForm" name="searchform" method="post" action="index.php?go" class="searchform">
<input type="text" name="search" value="" placeholder="Suchen..." class="field_search" id="tags">
</form>
Then add this javascript:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).on('submit', '#locationForm, #searchForm',function(e){
var locationInput = $('#locationForm input[name="location"]').clone();
locationInput.attr('type','hidden');
var searchInput = $('#searchForm input[name="search"]').clone();
searchInput.attr('type','hidden');
$('#locationForm').prepend(searchInput);
$('#searchForm').prepend(locationInput);
});
</script>
The javascript will add the search field to the location form and visa versa before submitting. So whenever you submit one of the forms, you will always have both values.
EDIT
In your corresponding.php you could use something like this if there are two seperate queries needed.
if(isset($_POST['search']))
{
$sql="SELECT * FROM table WHERE Name LIKE '%".$input."%' OR Description LIKE '%".$input."%'";
//Execute query
//Fetch results
}
if(isset($_POST['location']))
{
$sql="SELECT * FROM table WHERE Postcode LIKE '%".$input_location."%' OR City LIKE '%".$input_location."%' OR Combined LIKE '%".$input_location."%' OR Combined2 LIKE '%".$input_location."%'";
//Execute query
//Fetch results
}
//Combine results of search and location query
//echo results
Or if it's possible to execute one query you can use this:
if(isset($_POST['search']) && isset($_POST['location']))
{
$sql="HERE YOUR QUERY WHERE YOU CAN USE $_POST['search'] AND $_POST['location']";
//Execute query
//Fetch results
}
//Combine results of search and location query
//echo results

php searching in more than one column mysql

I am trying to make a code to search for data in more than one column , the code works only if I search in one column. when I tried to search in two columns it says that nothing is found in the database.
<form action="" method="post">
<input type="text" name="param" >
<input type="submit" name="submit" value="search">
</form>
if (isset($_POST['param'])) {
$param= trim ($_POST['param']);
$result = "SELECT * FROM table WHERE student_Name LIKE '%$param%' AND course_name LIKE '%$param%'";
I think you should use OR unless you want to check the 2 columns with the same parameter.
$result = "SELECT * FROM thecars WHERE student_Name LIKE '%$param%' OR course_name LIKE '%$param%'";
Also, this is very open to SQL injection. Sanitize your input before you pass it to the query.
You could do a concat and search via that.
$result = "SELECT * FROM thecars WHERE CONCAT(`student_Name`, `course_name`) AS `search`LIKE '%$param%'";
Your using the same $param variable to search on both columns. If your searching for 2 separate values provide a form that supports inputting 2 values. And then handle such input properly in your query formation.
<form action="" method="post">
<input type="text" name="param1" >
<input type="text" name="param2" >
<input type="submit" name="submit" value="search">
</form>
if (isset($_POST['param1']) || isset($_POST['param2'])) {
$param1 = trim ($_POST['param1']);
$param2 = trim ($_POST['param2']);
$result = "SELECT * FROM thecars WHERE student_Name LIKE '%$param1%' AND course_name LIKE '%$param2%'";
Also change your column aggregation in where clause to OR as suggested by others if your searching for similar outcome.

Issue using 2 fields in PHP form to retrieve information from a MySQL Database

I have a MySQL database with 3 columns:
id | articletitle | articleorganization
And a simple PHP form with 2 fields and a submit button: search.php
<div class="content">
<form id="form1" name="form1" method="post" action="searchdb.php">
<table width="100%" border="0" cellpadding="6">
<tr>
<td width="29%" align="right">Article Title:</td>
<td width="71%" align="left"><input name="title" type="text" id="articletitle" size="50" /></td>
</tr>
<tr>
<td align="right">Author or Organization:</td>
<td align="left"><input name="organization" type="text" id="articleorganization" size="50" /></td>
</tr>
</table>
<table width="100%" border="0" cellpadding="6">
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</form>
</div>
The form connects to searchdb.php:
<?php
include('settings.php');
$title = mysql_real_escape_string($_POST['title']);
$organization = mysql_real_escape_string($_POST['organization']);
$sql = "SELECT * FROM articles WHERE 1 "
. (isset($title) ? "AND articletitle LIKE '$title%' " : "")
. (isset($organization) ? "AND articleorganization LIKE '$organization%'" : "");
while ($row = mysql_query($sql)){
echo '<br/> Article Title: '.$row['articletitle'];
echo '<br/> Article Organization: '.$row['articleorganization'];
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo '<td>View Full Entry</td>';
echo '<br/><br/>';
}
?>
After some revision with the help of commenters the problem has changed.
Now, upon submitting a search, the results page begins scrolling the table that is created via searchdb.php over and over again, though without any results in the table.
If you echo your query, it will print something like this:
select * from articles where articletitle like '%%'
That's why your code returning all rows from the table. To make it work the way you want, change the name of your <input> to match with your columns.
<input type="text" name="title" />
<input type="text" name="organization" />
Given these tags, you'll have $_POST contains array like this:
Array
(
[title] => 'some value',
[organization] => 'another value',
)
And you have to perform some logic in your query. If only title is supplied,
SELECT * FROM articles WHERE articletitle LIKE '%$title%'
If only organization is supplied,
SELECT * FROM articles WHERE articleorganization LIKE '%$organization%'
If both are supplied,
SELECT * FROM articles
WHERE articletitle LIKE '%$title%' AND
articleorganization LIKE '%$organization%'
Here's the PHP to make SQL like above:
// Don't forget to properly escape your input
$title = mysql_real_escape_string($_POST['title']);
$organization = mysql_real_escape_string($_POST['organization']);
// Build the SQL
// Echo this string to make sure the SQL is correct
$sql = "SELECT * FROM articles WHERE 1 "
. (strlen($title) ? "AND articletitle LIKE '%$title%' " : "")
. (strlen($organization) ? "AND articleorganization LIKE '%$organization%'" : "");
$qry = mysql_query($sql);
Basically, when you have several items with the same name referencing some kind of array what you get is an actual array afterwards.
That is to say that if the input boxes are filled with "a" and "b" the variable $_POST['term'] will be equal to array("a", "b").
With regards to indenting, it is part of your code style, do it whatever way you feel comfortable with as long as you are consistent across your whole code base.
Edit: I do agree with others that you should be a lot more careful with user input and how you add that data to your queries
$_POST[term] becomes an array with key's like 0,1. Loosing the field reference for your SQL query.
Use these names in your input fields:
<input name="articletitle" type="text" id="articletitle" size="50" />
<input name="articleorganization" type="text" id="articleorganization" size="50" />
You can build your query like this:
$sql = mysql_query("select * from articles WHERE articletitle LIKE '%".mysql_real_escape_string($_POST['articletitle'])."%' OR articleorganization LIKE '%".mysql_real_escape_string($_POST['articleorganization'])."%'");
Note: Never ever use $_POST (user input) vars in a query without escaping first to prevent mysql injection.
PS My personal taste on indenting is: Always indent every block of matching HTML elements. So yes, I would indent the table one tab further.

Match key words in PHP

i have a search function on my website where users can search for products. it works perfectly fine except for the fact that when a user searches for 'ipod' it comes up with no result as the name of the product is 'apple ipod'. how do i code it so that when part of the name of the product is searched, the correct product comes up?
my code is as follows:
<div id="search" align="right">
<form action="" method="get">
<span id="sprytextfield1">
<input name="search" id="search2" type="text" width="250px"/>
<span class="textfieldRequiredMsg"></span></span>
<input name="" type="submit" value="Search"/>
</form></div>
<br /><br />
<h2>Your Search Results For "<?php echo $_GET['search'] ?>":</h2><hr />
<table border="0" cellpadding="2px" width="600px">
<?
$search = $_GET['search'];
$result=mysql_query("select * from products WHERE name = '$search'")
or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo ' '.'Could Not Be Found';
}
else {
while($row=mysql_fetch_array($result)){
?>
<tr>
<td><?php echo'<img src="getImage.php?id=' . $row['serial'] .'"/>'
?> </td>
<td> <b><?=$row['name']?></b><br />
Price:<big style="color:green">
£<?=$row['price']?></big><br /><br />
<input type="button" value="Add to Cart" onclick="addtocart(<?=$row['serial']?>)" />
</td>
</tr>
<tr><td colspan="2"><hr size="1" /></td>
<?
}
}?>
</table>
thanks for any advice given! :)
Ignoring the fact that your code should never be used for production (it's unsafe), you should use a LIKE in your query.
mysql_query("select * from products WHERE name LIKE '%$search%'")
Now, optimized against SQL injections and other things you don't want, this would become:
mysql_query("select * from products WHERE name LIKE '%".mysql_real_escape_string($search)."%'")
You can use a LIKE statement, like so
select * from products WHERE name LIKE '%$search%'
The above will match both 'apple ipod', 'ipod' and 'apple ipod'
Searching keyword in a table (eg: your product list) LIKE can be very useful but doesn't perform well on long text fields (eg: description), so consider also full text index and the MATCH () AGAINST operator.
Here mysql manual page
To avoid to return the page No results found, sorry, (after a none results query) you can use the SOUNDEX operator
mysql_query("select * from products WHERE SOUNDEX(name) > 0 ORDER BY SOUNDEX(name) DESC" ):
Here mysql soundex manual page

Categories