mysql multiple word search - php

i have a mysql table and a search form
i am filtering the table acc to the given conditions
but my problem is i want to search multiple words from string field
could you please help me how to do this :
i mean i want to allow it to be written multiple words in the string and want them to be searched by "AND"
if ($_REQUEST["string"]<>'') {
$search_string = " AND (customername LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR definition LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%')";
}
if ($_REQUEST["customername"]<>'') {
$search_customername = " AND customername='".mysql_real_escape_string($_REQUEST["customername"])."'";
}
if ($_REQUEST["date"]<>'' and ($_REQUEST["string"]<>'' or $_REQUEST["customername"]<>'') ) {
$sql = "SELECT * from ".$SETTINGS["data_table"]." WHERE date = '".mysql_real_escape_string($_REQUEST["date"])."' ".$search_string.$search_customername;
} else
if ($_REQUEST["date"]<>'' and ($_REQUEST["string"]<>'' or $_REQUEST["customername"]<>'' ) ) {
$sql = "SELECT * from ".$SETTINGS["data_table"]." WHERE date = '".mysql_real_escape_string($_REQUEST["date"])."' ".$search_string.$search_customername;
} else
if ($_REQUEST["date"]<>'' and $_REQUEST["string"]=='' and $_REQUEST["customername"]=='') {
$sql = "SELECT * from ".$SETTINGS["data_table"]." WHERE date = '".mysql_real_escape_string($_REQUEST["date"])."' ";
} else {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE id>0".$search_string.$search_customername;
}

Related

How can I search multiple inputs from a form in php?

I have a PHP program that allows users to search through an SQL table depending on the input or combination of inputs. I can do single search combination, but can't figure out a way to search by any criteria. What I got so far is terrible because I'm trying to search by every input possibility (and it's not working). This is what I got so far.
<?php
include_once("config.php");
if(isset($_POST['submit'])){
$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$day = mysqli_real_escape_string($mysqli, $_POST['day']);
$month = mysqli_real_escape_string($mysqli, $_POST['month']);
$year = mysqli_real_escape_string($mysqli, $_POST['year']);
// 1 2 3 4
if( !empty($name) && !empty($day) && !empty($month) && !empty($year) ) {
$sql = mysqli_query($mysqli, "SELECT *
FROM transfer
WHERE name like '%$name%'
and day LIKE '%$day%'
AND month LIKE '%$month%'
AND year LIKE '%$year%'");
} else if (!empty($name) && !empty($day) && !empty($month) ) {
$sql = mysqli_query($mysqli, "SELECT *
FROM transfer
WHERE name like '%$name%'
and day LIKE '%$day%'
AND month LIKE '%$month%'");
} else if (!empty($day) && !empty($month) && !empty($year) ) {
$sql = mysqli_query($mysqli, "SELECT *
FROM transfer
WHERE day LIKE '%$day%'
AND month LIKE '%$month%'
AND year LIKE '%$year%'");
} else if (!empty($name && !empty($day) ) {
$sql = mysqli_query($mysqli, "SELECT * FROM transfer
WHERE name like '%$name%' and
day LIKE '%$day%'");
}
//1 3
else if (!empty($name) && !empty($month) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE name like '%$name%' and month LIKE '%$month%'");
}
//1 4
else if (!empty($name) && !empty($year) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE name like '%$name%' and year LIKE '%$year%'");
}
//2 3
else if (!empty($day) && !empty($month) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%' and month LIKE '%$month%'");
}
//2 3
else if (!empty($day) && !empty($month) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%' and month LIKE '%$month%'");
}
//2 4
else if (!empty($day) && !empty($year))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%' and year LIKE '%$year%'");
}
//3 4
else if (!empty($month) && !empty($year))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE month like '%$month%' and year LIKE '%$year%'");
}
//1
else if (!empty($name))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE name like '%$name%'");
}
//2
else if (!empty($day))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%'");
}
//3
else if (!empty($month))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE month like '%$month%'");
}
//4
else if(!empty($year))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE year like '%$year%'");
}
else
{
echo "<p>you must insert an input</p>";
}
//while loop used to retrieve data from the SQL database
while ($res = mysqli_fetch_array($sql))
{
echo "<tr>";
echo "<td>".$res['name']."</td>";
echo "<td>".$res['confirmation']."</td>";
echo "<td>".$res['code']."</td>";
echo "<td>".$res['hora']." ".$res['horario']."</td>";
echo "<td>".$res['day']."/".$res['month']."/".$res['year']."</td>";
echo "<td>".$res['extra']."</td>";
echo "</tr>";
}
}
?>
</table>
(Note: It has been said to use prepared statements, which is right - but I don't want to give a copy & paste answer anyway, so here is just an example on how you can achieve your result - use prepared statements anyway. It works the same, except you are creating your query with placeholders and provide the variables that are not empty)
You can create your query in a more "dynamic" way. This is a little tricky, and becomes very "challenging" if joins are required - but what you actually want is to end up with a single query, containing all your constraints.
The first thing, you should define: Are your Searchfields "and" or "or" fields?
if it's "and" it is quite simple to achieve - something like this:
$query = "SELECT * FROM transfer";
$andParts = array();
if(!empty($name))
$andParts[] = "name = '$name'";
if(!empty($day))
$andParts[] = "day = $day";
if (!empty($month))
$andParts[] = "month = $month";
if (!empty($year))
$andParts[] = "year = $year";
if (!empty($andParts))
$query .= " WHERE ".implode(" AND " , $andParts);
$sql->Query($query);
if theres also "or" involved, you'll need another array $orParts, where you first join all the "ors", and finally glue that array together to the final "ands".
If conditions could match columns from "joined" tables, you need to keep track of that, so that you know, from with tables you need to "select".
If you have very complex query for each "searchfield" (i.e. every searchfields result is a result of multiple joins etc...) you can query just the id's for each searchfield, then intersect the results and retrieve the ids matching all criterias:
$result1 = $sql->Query("SELECT id FROM transfer left join .... ");
// array(1,2,3,5,7,10,15,19,27)
$result2 = $sql->Query("SELECT id FROM transfer right join .... ");
// array(2,3,10,15,19,27,43,123)
$result3 = $sql->Query("SELECT id FROM transfer inner join .... ");
// array(2,10,15,27,43,711)
$ids = array_intersect($result1, $result2, $result3);
// array(2,10,15,27)
$finalResult = $sql->Query("SELECT * FROM transfer WHERE id in (".implode(",", $ids).");");

Search multiple values if present

sorry my English is weak ....
how can i search multi values from db SQL So that there was any.
i can search name && family together but
I want when the user searched name And family leave empty Return result correctly
how can i write this
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE name='{$_POST['searchname']}' && family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Your 3 main issues here..
the first being WHERE name= now.. name is already used by mysql therefore you shouldn't use it however.. If you do use it run it like this:
WHERE `name`=
You should always backtick database tables and columns to make life easier in the long haul.
The second issue being you used && where it should be AND
the third is you shouldn't be placing your variables straight into your query as you're left open for SQL Injection.
Now I'm running on the assumption you're using $mysqli as your variable however, this may need adjusting to suit the correct variable you are using:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$searchName = $_POST['searchname'];
$family = $_POST['searchfamily'];
$sql = $mysqli->prepare("select * from `myinfo` WHERE `name` = ? OR `family`= ? ORDER BY `id` DESC");
$sql->execute([$searchName, $family]);
} else {
$sql = $mysqli->prepare("select * from `myinfo` ORDER BY `id` DESC");
$sql->execute();
}
If you want to search with both then you need to change your if also. And change && to and in your query
if (isset($_POST['searchname']) && isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE `name`='{$_POST['searchname']}' AND family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Edit
As per your comment try this:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$where="";
if(isset($_POST['searchname']))
$where=" WHERE `name`='{$_POST['searchname']}'";
if(isset($_POST['searchfamily']))
{
if($where=="")
$where=" WHERE family='{$_POST['searchfamily']}'";
else
$where=" AND family='{$_POST['searchfamily']}'";
}
$sql = "select * from myinfo $where ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}

PHP elseif statement defaults to first block

I am trying the following elseif statement to call the correct code based on a POST from the previous page and it has been defaulting to using only the first block of code i am aware that this might not be the best way to carry out the code in this situation so i'd like to ask if anyone has a more efficient way of doing this THANKS
elseif ($toyota="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%toyota%'";
}
elseif ($bmw="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Bmw%'";
}
elseif ($subaru="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Subaru%'";
}
elseif ($mitsubishi="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mitsubi%'";
}
elseif ($nissan="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Nissan%'";
}
elseif ($mazda="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mazda%'";
}
elseif ($chrysler="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Chrysler%'";
}
Forgot to mention,the post from html comes like
"toyota=on", "bmw=on" and so on
$cars = array('toyota', 'bmw', 'nissan');
foreach ($cars as $car) {
if (!isset($_POST[$car]) || $_POST[$car] != 'on') {
continue;
}
$query = "SELECT * FROM `products` WHERE name LIKE '%$car%'";
break;
}
There is difference between = and ==.
= assigns value, whereas == compares value.
replace all your = with ==
($toyota=="on"){
There is much better way to do that instead of using so many if else blocks. try using a varibale in the query based on the input.
A single = will set a value whereas a double == will test for equality
elseif ($toyota=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%toyota%'";
}
elseif ($bmw=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Bmw%'";
}
elseif ($subaru=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Subaru%'";
}
elseif ($mitsubishi=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mitsubi%'";
}
elseif ($nissan=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Nissan%'";
}
elseif ($mazda=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mazda%'";
}
elseif ($chrysler=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Chrysler%'";
}

PHP Select from multiple tables and add value together to get total

i am trying to run these queries in PHP to a mysql table
$sql="SELECT * from customer where customerid > '' and voicemail_max > '' and company_status = '' ";
$rs=mysql_query($sql,$conn);
while($customer=mysql_fetch_array($rs)) {
$sql2="SELECT * from client where parent_client_id = '".$customer["customerid"]."' ";
$rs2=mysql_query($sql2,$pbx01_conn);
while($result2=mysql_fetch_array($rs2))
{
$sql3="SELECT * from extension where client_id = '".substr($result2["id"],1,3)."' ";
$rs3=mysql_query($sql3,$pbx01_conn);
while($result3=mysql_fetch_array($rs3))
{
$sql4="SELECT * from extension_voicemail where extension_id = '".$result3["id"]."' ";
$rs4=mysql_query($sql4,$pbx01_conn);
$voicemail_size_total=0;
while($result4=mysql_fetch_array($rs4)) {
$voicemail_size_total = $voicemail_size_total+$result4["filesize"];
}
}
}
echo $voicemail_size_total;
}
it should be adding up multiple values from one column
the $sql4 query looks like:
SELECT * from extension_voicemail where extension_id = '1454'
and when i run that in the database, it returns one row with the file size column as 31780
but when i echo $voicemail_size_total variable, it shows nothing.
it works fine if i echo that variable one line up from where it is, but where it is now shows nothing
Declare $voicemail_size_total=0; outside of all of the while loops. Everytime you get back to the loop you re-set that back to 0. That might be the problem.
Well, it depends on what you want to achieve:
1. If you want to get a total of all the filesizes (basicly you are expecting just one value to be presented ) try this:
$sql="SELECT * from customer where customerid > '' and voicemail_max > '' and company_status = '' ";
$rs=mysql_query($sql,$conn);
$voicemail_size_total=0;
while($customer=mysql_fetch_array($rs)) {
$sql2="SELECT * from client where parent_client_id = '".$customer["customerid"]."' ";
$rs2=mysql_query($sql2,$pbx01_conn);
while($result2=mysql_fetch_array($rs2))
{
$sql3="SELECT * from extension where client_id = '".substr($result2["id"],1,3)."' ";
$rs3=mysql_query($sql3,$pbx01_conn);
while($result3=mysql_fetch_array($rs3))
{
$sql4="SELECT * from extension_voicemail where extension_id = '".$result3["id"]."' ";
$rs4=mysql_query($sql4,$pbx01_conn);
while($result4=mysql_fetch_array($rs4)) {
$voicemail_size_total = $voicemail_size_total+$result4["filesize"];
}
}
}
}
echo $voicemail_size_total;
2. If you're looking for the filesizes of each client (ie. expecting a series of filesizes to be presented ) try this:
$sql="SELECT * from customer where customerid > '' and voicemail_max > '' and company_status = '' ";
$rs=mysql_query($sql,$conn);
while($customer=mysql_fetch_array($rs)) {
$sql2="SELECT * from client where parent_client_id = '".$customer["customerid"]."' ";
$rs2=mysql_query($sql2,$pbx01_conn);
$voicemail_size_total=0;
while($result2=mysql_fetch_array($rs2))
{
$sql3="SELECT * from extension where client_id = '".substr($result2["id"],1,3)."' ";
$rs3=mysql_query($sql3,$pbx01_conn);
while($result3=mysql_fetch_array($rs3))
{
$sql4="SELECT * from extension_voicemail where extension_id = '".$result3["id"]."' ";
$rs4=mysql_query($sql4,$pbx01_conn);
while($result4=mysql_fetch_array($rs4)) {
$voicemail_size_total = $voicemail_size_total+$result4["filesize"];
}
}
}
echo $voicemail_size_total;
}

How can execute a MySQL query with multiple WHERE-clauses?

how would you do a mysql query where a user can choose from multiple options. Fox example I have a form that user can use to search for houses. Now I have a select box where you can chosse whether you want a house, a flat or whatever. Then I have a second box where you can choose for example the city you want the house or flat to be in. And maybe another one with the maximum price.
Now how would you do the mysql query? My problem is, I would do it like that:
if($_POST["house_type"] != 0) {
$select = mysql_query("SELECT * FROM whatever WHERE type = '".$_POST["house_type"]."'");
}
But now I only have the case that someone has chosen a house type but not any other option. So do I have to do an "if" for every possible combination of selected elements?
To emphasize my problem:
if(!isset($_POST["house_type"])) {
if($_POST["something"] == 0) {
$search_select = #mysql_query("SELECT * FROM housedata WHERE something = $_POST["whatever"]);
}
elseif($_POST["something"] != 0) {
$search_select = #mysql_query("SELECT * FROM housedata something = $_POST["whatever"] AND somethingelse = 'whatever');
}
}
elseif(!isset($_POST["house_type"])) {
if($_POST["something"] == 0) {
$search_select = #mysql_query("SELECT * FROM housedata WHERE something = $_POST["whatever"]);
}
elseif($_POST["something"] != 0) {
$search_select = #mysql_query("SELECT * FROM housedata something = $_POST["whatever"] AND somethingelse = 'whatever');
}
}
Now imagine I had like 10 or 20 different select boxes, input fields and checkboxes and I would have to do a mysql query depending on what of these boxes and fiels and checkboxes is filled. This would be a code that is extremely complicated, slow and horrible. So is there a possibility to make a mysql query like:
SELECT * FROM whatever WHERE house_data = '".$whatever."' AND (if(isset($_POST["something"])) { whatever = '".$whatever2."' } AND ...;
You get what I mean? Its a bit complicated to explain but actually its a very important question and probably easy to answer.
Thank you for your help!
phpheini
Generate the WHERE clause prior to running the SQL.
A short example:
$whereClause = "";
if ($_POST['opt1']) {
$opt1 = mysql_real_escape_string($_POST['opt1']);
$whereClause .= "AND opt1='$opt1'";
}
if ($_POST['opt2']) {
$opt2 = mysql_real_escape_string($_POST['opt2']);
$whereClause .= "AND opt2='$opt2'";
}
mysql_query("SELECT * FROM table WHERE 1 ".$whereClause);
To point you a little bit into the right direction, try something like this:
if(isset($_POST["something"]))
{
$where = " AND whatever = '".$whatever2."'";
}
else $where = '';
mysql_query("SELECT * FROM whatever WHERE house_data = '".$whatever."'".$where);
$where = array();
if($_POST["something"]) {
$where[] = " something =".$_POST["something"];
}
if($_POST["something2"]) {
$where[] = " something2=".$_POST["something2"];
}
.
.
.
//build where string
$where_ = !(empty($where) ? " WHERE ".implode(" AND ",$where) : "";
//build sql
$sql = "SELECT * ... ".$where;
write some simple query builder
$where = array();
if($_POST["something"]) {
$where[] = sprintf(" something='%s'",$_POST["something"]);
//sprintf - prevent SQL injection
}
if($_POST["something2"]) {
$where[] = sprintf(" something2='%s'",$_POST["something2"]);
}
//build where string
$where_str = " WHERE ".implode(" AND ",$where);
//build sql
$sql = "SELECT * ... $where_str";
You need to build your search string separately but the format is simply
SELECT * FROM your_table WHERE number = {$number} AND sentence = '{$sentence}';
Since you are creating the search term based on PHP logic do this:
$search = "SELECT * FROM your_table WHERE ";
if(isset($whatever)) $search .= "something = '{$whatever}'";
if(isset($whateverelse)) $search .= " AND somethingelse = '{$whateverelse}'";
$search_select = mysql_query($search);

Categories