How i will make a LIKE search in the following code? - php

I've got the following code which is something like a form search engine with multiple inputs where the results are kinda absolute concerning the number of characters etc(perfect match)
.
// build array of field names=============================================================================
$fields=array('user','customer','vessel','country',
'port','eta','service_station','type_of_service',
'case_reference','status');
// initialize empty array for WHERE clauses
$wheres=array();
// loop through field names, get POSTed values,
// and build array of WHERE clauses, excluding false values
foreach ($fields as $field) {
// get existing field value from POST, mark missing or empty value as FALSE
${$field} = isset($_POST[$field]) && trim($_POST[$field])!=''
? trim($_POST[$field]) : false;
// add to array of WHERE clauses only if value is not FALSE
if (${$field}) { $wheres[]="$field='".${$field}."'"; }
}
// build SELECT statement from WHERE clauses
$sql="SELECT * FROM jobs WHERE ".
(!empty($wheres) ? implode(" AND ",$wheres) : '1=1').
";";
What i want to do is add an input in the form
<label for="special">Special Search</label>
<input type="text" name="special" id="special_search">
where the user would be able to search in the case_reference field and get the results that match the first four characters. Also i would like this new input to work the same as the others as far as the AND or OR and TRUE or FALSE statements are concerned.
All help appreciated thank you in advance:)
UPDATE : Instead of rewriting the whole thing i came up with the following code at the begining of my previous :
$joker = $_POST['special'];
$joker1 = substr($joker1, 0, 4);
if(isset($_POST['case_reference']) && !empty($_POST['case_reference'])
&& empty($_POST['special'])) {
} else { $_POST['case_reference'] = $joker1; }
It is working for now but anyone can confirm that it would be okay in future??

From the SQL:
$sql="SELECT * FROM jobs WHERE ". (!empty($wheres) ? implode(" AND ",$wheres) : '1=1').";";
Just simply add a variable for special:
$special = $_POST['special']; // this will get the data from the textbox
then add it to the sql statement
$sql="SELECT * FROM jobs WHERE LIKE $special 'aaaa%' AND ". (!empty($wheres) ? implode(" AND ",$wheres) : '1=1').";";

Rewritten avoiding variable variable names, and using mysql_real_escape_string (although you should use mysqli or pdo):-
<?php
// build array of field names=============================================================================
$fields=array('user','customer','vessel','country',
'port','eta','service_station','type_of_service',
'case_reference','status');
// initialize empty array for WHERE clauses
$wheres = array('1=1');
// loop through field names, get POSTed values,
// and build array of WHERE clauses, excluding false values
foreach ($fields as $field)
{
// get existing field value from POST, mark missing or empty value as FALSE
if (isset($_POST[$field]) && trim($_POST[$field])!='')
{
$wheres[]="`$field`='".mysql_real_escape_string(trim($_POST[$field]))."'";
}
}
if (isset($_POST['special']) && trim($_POST['special'])!='')
{
$wheres[] = " case_reference' LIKE '".mysql_real_escape_string(trim($_POST['special']))."%'";
)
// build SELECT statement from WHERE clauses
$sql="SELECT * FROM jobs WHERE (".implode(" AND ",$wheres).") ;";
?>

Related

laravel eloquent - check if all values of array in table

I have a table options and I have an array of strings ["value1", "value2", "value3"].
What I'd like to do is check if all of the values within the array are present in the table.
I've tried whereIn but I think it checks if any values exist in the table.
This is what I have done currently:
$v = ["value1", "value2", "value3"];
$options = Options::whereIn('value', $v)->get();
if ($options->count() != count($v)) {
//something must be missing
}
This works, but I wonder if there is a better way? The table has millions of records so I'd like to do only 1 query if possible.
Thanks!
The answer in the comments by justcarty is technically correct, but you can reduce the load by not pulling in the options if you don't intend to use them.
if (Option::whereIn('value', [...])->count() != count([...])) {
//perform action
}
Also note, as justcarty mentioned, this won't work if you have multiple occurrences of a value in your database, but you can get around this by adding DISTINCT clause to your query.
if (Option::distinct(['value'])->whereIn('value', [...])->count() != count([...])) {
//perform action
}
whereIn check specifically for that one value in the arrays.
You can try this:
$search_values = ['value1', 'value2', 'value3'];
$found = true;
foreach ($search_values as $search) {
if (!Search::where('column', $search)->first()) {
$found = false;
}
}
if (!$found) {
// Something must be missing
}

Search Using IN Condition in MySql

I am writing Web services for IOS In cakePhp and stuck in IN condition.
I have a table dog_temperaments and it has values "happy,dependent,shy".
Now if IOS send me array (happy,shy) Then I search Like this
Select dog_temperaments.* where temperaments IN(happy,shy)
Its work fine but if IOS send me array 0 or any(means search by any temperament) Then How I will Search........
Any means Search by all temperaments
If it is 0 or any any then no need for that condition as it ishould return all of them.
So aassuming $type will contain the temperaments as an array and 0/any will be single element for that case.
if(count($type) == 1 && in_array(($type[0], array('0', 'any'))) {
$condition = "";
} else {
$condition = "WHERE temperaments IN ('" . implode("','", $type) . "')";
}
And the query will be like -
"Select dog_temperaments.* from dog_temperaments ".$condition
Either you can check that the array is empty or not like
if(is_array($array)) {
Use
Select dog_temperaments.* where temperaments IN('happy','shy');
} else {
notify Enter proper search key
}
Else you anyways get the empty results by using the same query if the array is empty like
Select dog_temperaments.* where temperaments IN(0);

How can explode a words from field with multiple values?

I have this table: TABLE_ELEMENTS, with the name ELEMENTS, i have a multiple values inside, see image.
This is the php and return the results from autocomplete request.
$("#autocomplete").autocomplete({
source: "http://localhost/include/autocomplete.php?type=mauto_complete",
First i call this..
if(isset($_GET['type']) && in_array($_GET['type'], $arr_action)) $type=$_GET['type'];
if($type == "mauto_complete") {
require_once $config_abs_path."/autocomplete/autocomplete.php";
if(isset($_GET['term'])) {
$term = escape($_GET['term']);
$response = mauto_complete::getAutocomplete($term);
echo json_encode($response);
}
}
And this is the secondauto.php file
function getAutocomplete($term) {
global $db;
global $config_table_prefix;
global $crt_lang;
$elements=$db->fetchRow("select Distinct `elements` from TABLE_ELEMENTS where `elements` like '$term%' limit 10");
$elements_array = explode("|", $elements);
return $elements_array;
}
I have write this after select
$elements_array = explode("|", $elements);
Ok the request is working fine, but in autocomplete results when i type the word Building i take no words.
But when i type the first word of the elements ( Apartment ) i take all words.
The words is not uniqe
A common approach to this is to add a | to the left of the field, then search that. This ensures that an element containing the search doesn't get matched.
select
Distinct `elements`
from
TABLE_ELEMENTS
where
lower(CONCAT('|', `elements`)) LIKE lower('%|$term%')
However, you're probably looking for something else. Below is how I'd approach it. I couldn't figure out what library you were using for your connection, so you may have to change a little bit for it to work for you.
function getAutocomplete($name, $term)
{
// make sure you escape the string to avoid SQL injection
$name = mysqli_real_escape_string($db, $name);
// make the searches case-insensitive
$term = strtolower($term);
// fetch the valid elements for the field and split them using explode
$elements = $db->fetchRow("SELECT `elements` FROM `TABLE_ELEMENTS` WHERE `name` = '$name'");
$elements_array = explode('|', $elements);
// make an array to save the matching elements
$filtered = array();
// iterate over each element to check for a match
foreach($elements_array as $element)
{
// check to see if the beginning of the element starts with the search term
if(strpos(strtolower($element), $term) === 0)
{
// add it to the filtered array
$filtered[] = $element;
}
}
// return the matching results
return $filtered;
}
Then to use it, specify what field you want to autocomplete for:
print_r(getAutocomplete('Property Type', 'B'));
// Outputs: Array
// (
// [0] => Building
// [1] => Bungalow
// [2] => Business
// )
To make your existing code to use it, change your JavaScript to match the following. You'll need to change name depending on what field you're autocompleting.
$("#autocomplete").autocomplete({
source: "http://localhost/include/autocomplete.php?type=mauto_complete&name=Property%20Type"
});
Then update the file where you call the getAutocomplete function:
if(isset($_GET['type']) && in_array($_GET['type'], $arr_action)) $type=$_GET['type'];
if($type == "mauto_complete") {
require_once $config_abs_path."/autocomplete/autocomplete.php";
if(isset($_GET['term']) && isset($_GET['name'])) {
$name = $_GET['name'];
$term = $_GET['term'];
$response = mauto_complete::getAutocomplete($name, $term);
echo json_encode($response);
}
}
Try use like this to get all possible results
$elements=$db->fetchRow("select distinct `elements` from TABLE_ELEMENTS where lower(`elements`) like lower('%$term%') limit 10");

For loop for two tables

if(count($search)==0) {
for($i=0;$i<count($about);$i++) {
$bd->insert("search","page_title,page_description,page_url,image_id","'About','{$about[$i]['image_title']}','http://religiousbrands.in/demo/about.php?search=".$about[$i]['id']."','{$about[$i]['uniq_id']}'");
}
} else {
for($i=0;$i<count($about);$i++) {
for($k=0,$j=0;$k<=$i,$j<count($search);$j++,$k++) {
if($search[$j]['image_id']==$about[$i]['uniq_id']) {
echo "update".$i.'and'.$k.'and'.$j;
echo"<br>";
$bd->update("search",
"page_title='About',page_description='{$about[$i]['image_title']}',page_url='http://religiousbrands.in/demo/about.php?search=".$about[$i]['id']."' ","image_id='{$about[$i]['uniq_id']}' limit 1");
}
}
}
}
$search is an array which I am getting from my database . first I m checking if the search table is empty or not . if empty then insert the values in the search table .
$about is also an array which i am getting from my database . if $search is not empty Then I am updating the value but checking first that $search[$j]['image_id']===$about[$i][uniq_id] and HERE IS MY PROBLEM START :
Suppose in my table about there are 3 entries ie :
uniq_id=1
uniq_id=2
uniq_id=3
and In my table search there are 2 entries ie:
image_id=1
image_id=2
So the search table is not empty So it will follow the 2nd condition. So i was trying that table $about[1]['uniq_id'] should check for $search[1]['image_id'] and $search[2]['image_id'] and etc $search[$i]['image_id'] if the table has any values
but I my for loop is not working like I want So anybody can help me in this
You'll need to know which rows in the "search" table need adding (INSERT) and which ones need updating.
Perhaps try looping through the "search" array first and find which "image_id" values you have.
$image_ids = array();
foreach ($search as $item) {
$image_ids[] = $item['image_id'];
}
Next, loop through the "about" array. Use the ID's in the "$image_ids" array to determine whether you need to UPDATE or INSERT an item.
foreach ($about as $item) {
if (in_array($item['image_id'], $image_ids)) {
// Item already exists. Update it.
} else {
// Item doesn't exist. Add it.
}
}
This is also much faster than putting loops inside loops.

MySQL / PHP - User filter variable to return all values

Thanks in advance for checking out this question.
I have a series of HTML select elements where a user can define what data they want returning from the MySQL database. Each of the choices are stored in a variable. Some of the options enable the user to choose "No Preference" in which case the sql statement needs to accept a variable allowing it to return all the fields of that specific column.
I am using PHP for reference.
Does this exist or is it a poor code set up ? currently the SQL statement is accepting the variables in this format
AND `operationalTier1`='$userOps'
AND `modelName`='$userEndpoint'
AND `status`='$userStatus'
AND `sourceName`='$userSource'
AND `metSLA`='$userSLA'
The Select for the user to choose from is in this format
<h3>Data Filters</h3>
<p>Case Created</p>
<form action="index.php" method="post">
<p>Ops Tier 1</p>
<select name="ops_1_select">
<option>No Preference</option>
<option>Add/Create</option>
<option>Delete/Remove</option>
<option>Fix</option>
<option>Inform</option>
</select>
Setting the option to a variable
if ($_POST['ops_1_select'] = "No Preference")
{
$userOps= XXXX
} else
{
$userOps= $_POST['ops_1_select'];
}
So If the user selects "No preference" I need the variable to store something that will return all of the ops tiers from the db which would replace XXXX
In your if statement you should be using an equality operator (==) and not an assignment operator (=). That if statement will always result to true and it will set the value of the $_POST key you've selected. Change if ($_POST['ops_1_select'] = "No Preference") to if ($_POST['ops_1_select'] == "No Preference")
Before:
if ($_POST['ops_1_select'] = "No Preference")
{
$userOps= XXXX
} else
{
$userOps= $_POST['ops_1_select'];
}
After:
if ($_POST['ops_1_select'] == "No Preference") {
$userOps = "XXXX";
} else {
$userOps = $_POST['ops_1_select'];
}
You can find some more information here
So, based on your comments on this answer I'll share a little more code I think might help:
$fields = array('field1', 'field2', 'field3');
$query = 'text'; // should be everything up until your first WHERE
for ($fields as $key => $val) {
if ($_POST[$val] == 'No Preference') {
// IS NOT NULL will return true as long as the field is set
$and = $val . ' IS NOT NULL';
} else {
$and = $val . ' = "' . $_POST[$val] . '"';
}
$query = $query . $and . ' AND ';
}
// Remove the trailing AND from $query, add anything else you need, run query
Some more notes, VALIDATE YOUR INPUT DATA! If you aren't using PDO/mysqli or another database abstraction engine, now is the time to start. As is this code is very vulnerable to SQL injection. Check out this question
I would use LIKE insted of = and add a %.
AND `operationalTier1` LIKE '$userOps'
And:
$userOps= '%';
Or you can remove the condition AND operationalTier1='$userOps' from your sql statement when No Preference is set.

Categories