Dynamic search query in MySQL - php

Here is the project installation:
1. Nodejs server side environment
2. MySQL database (with Knexjs query builder)
3. 'locations' table in a database with fields like 'country', 'city', 'category', 'working_hours'.
4. Form input where user can select all these values and submit the search. When the user selects nothing, it defaults to 'ALL'. I need to filter the database and to select rows corresponding to the user search input.
I tried to do something like this:
knex('locations').where({
country: countryInput,
city: cityInput,
category: categoryInput,
working_hours: hoursInput
})
.then(function(rows) {.....})
.catch(function(err) {.....});
This works well if user selects all the input fields, what if the user selects only few of them and other are set to 'all'? How to make this work?
Thank you in advance!

This is pretty common solution:
let query = knex('locations');
if (countryInput) {
query = query.where('country', countryInput);
}
if (cityInput) {
query = query.where('city', cityInput);
}
if (categoryInput) {
query = query.where('category', categoryInput);
}
if (hoursInput) {
query = query.where('working_hours', hoursInput);
}
query
.then(function(rows) {.....})
.catch(function(err) {.....});

you can modify your query using Modify
expecting req.query object matching your table columns-
knex('locations')
.modify(function(queryBuilder) {
if (req.query) {
queryBuilder.where(req.query);
}
})
.then(function(rows) {.....})
.catch(function(err) {.....});
well, there are some potential risk. You need filter your query first.

Related

How to iterate columns in datatable using jQuery? [duplicate]

I am using jquery plugin DataTables for building nice table
var table = $('#example').DataTable({
"data": source
});
I would like that make an each for all rows in table
Unfortunately this way may be out of date and does't work with new version (it launchs an error)
$(table.fnGetNodes()).each(function () {
});
And this way only works only for visibles rows (10 first rows because other rows are paginated)
table.each( function ( value, index ) {
console.log( 'Data in index: '+index+' is: '+value );
} );
Do you known how to loop to all rows please?
I finally found:
var data = table.rows().data();
data.each(function (value, index) {
console.log(`For index ${index}, data value is ${value}`);
});
Datatables have an iterator for each row rows().every() with this referring to the context of the current row being iterated.
tableName.rows().every(function(){
console.log(this.data());
});
If you are using the legacy DataTables then you can get all the rows even the paginated ones, as shown below...
table.fnGetNodes(); // table is the datatables object.
So we can loop through the rows by using .each() method provided by jQuery.
jQuery(table.fnGetNodes()).each(function () {
// You can use `jQuery(this).` to access each row, and process it further.
});
for example, this data has three fields UserID, UserName and isActive and we want to show only active users
The following code will return all the rows.
var data = $('#myDataTable').DataTable().rows().data();
We will print only active users
data.each(function (value, index) {
if (value.isActive)
{
console.log(value.UserID);
console.log(value.UserName);
}
});

CakePHP how to add data from another field of a related model

This is one of my first applications out of tutorials so I don't know how to express my issue well.
Well I have these 2 tables:
User ( id, code )
Hours ( id, user_id, created)
I want to know how I can add an entry to the Hours table using the user_code.
I tried to grab the data of the User table with the code value and then findBy and pass for the patchEntity but it did not work.
I don't have a whole lot of information to work with, but I'll give it a go.
I want to know how I can add an entry to the Hours table using the
user_code
You mention using patchEntity, so that's updating information that's already there. Assuming user_code is the 'code' column you're talking about there, first find the user by his code:
$users_tbl = TableRegistry::get('Users');
// find the user
$user = $users_tbl->findByCode($user_code)->first();
if ($user) {
// replace '$this->request->data() with whatever patch data you wanted
$users_tbl->patchEntity($user, $this->request->data(), [
'associated' => ['Hours']
]
if ($users_tbl->save($user)) {
// success!
} else {
// error!
}
} else {
// error!
}
It will also depend on how you have the data you passed in (where my '$this->request->data() is, or whatever your array might be) - it needs to match the right column names and be in the correct format listed here.
However, this is updating the data. Just adding the data, you can load the hours table and add a new entry with the user_id acquired from the user search:
$hours_tbl = TableRegistry::get('Hours');
$hours = $hours_tbl->newEntity([
'user_id' => $user->id // $user populated from same method earlier
]);
/* assumed 'id' was autoincrementing and 'created' was populated
through Timestamp behavior */
if ($hours_tbl->save($hours)) {
// yay!
} else {
// boo
}

How to select from mysql array text and compare

I am collecting user selected "text" as array in mysql using PDO connection from php form there are let suppose 3 check boxes with names
1- Apple
2- Banana
3- Cherry
In DB stored values are as per shown
apple,banana,cherry
What i want : I want to display "Apple" users in certain "/offer.php" page
while i am using SELECT query and it's not working i am using pure php mvc framwork.
In Controller i done this
public function offer(){
$this->view->title = User Selection;
$this->view->offerUser = $this->model->offerUser();
$this->view->render('dashboard/offer');
}
In Model I done this
public function offerUser()
{
return $this->db->select('SELECT * FROM users WHERE selection = apple ORDER BY points DESC ');
}
In View i done this
<?php
foreach($this->offerUser as $key => $value) {?>
<tbody>
<tr>
<td></td>
<td><strong><?php echo $value['selection']?></strong></td>
</tr>
The issue is i am not able to select "Text" from stored array with model and even not able to display selection in "View" user end page.
This code format was working fine with single numeric digit selection or compare but failed with text array.
Please help me out with this i really appreciate this i am new with text array fetching.
Hope someone answer my question soon....
Regards,
james
query is not working : use single quotation around apple
public function offerUser()
{
return $this->db->select("SELECT * FROM users WHERE selection = 'apple' ORDER BY points DESC ");
}

How to implement search form in codeigniter

I have asked this question before but i did not get the right answer. I have a table 'cv', i want to search for items in the database using two fields i.e. course and location, the two items are on the same table('cv'). I dont have an idea on how to implement the two searches.
The code below is for displaying search for course only and its working fine. Help me to use the two search criterions i.e.course and location or in other words how do i add the search for location input in my code.
Controller
function search_worker()
{
$data['query']=$this->kint_model->search_workers($this->input->post('search'));
$this->load->view('hire_display',$data);
}
Model
function search_workers($search)
{
return $query = $this->db->get_where('cv', array('course '=> $search))->result();
}
View
$data = array('name'=>'search', 'id'=>'search','value'=>'bcom');
echo form_input($data);
$data = array('name'=>'submit', 'id'=>'submit', 'value'=>'Search Item(s)');
echo form_submit($data);
Maybe you need a like clause in your query,
function search_workers($search){
//return $query = $this->db->get_where('cv', array('course '=> $search))->result();
return $this->db->like('course', $search)->like('location', $location)->get('cv')->result();
}
You should also get some basic SQL training.

how do I exclude table field MYSQL

Sorry about the strange title, but I am having a small issue if the user type is 2 or 3 then I need the user not to be able to insert or update a few fields, but instead of creating a number of insert queries listed below are a few fields I need not updated.
AMStatus,HQStatus,approvedforsite
public function databaseinsert($data)
{
$this->data = $data;
switch($this->data['action']){
case "newlead":
$this->insert("customer_detail",
"TradingName,Street,City,State,PostCode,Industry,SubCategories,Membership,LeadStatus,AMStatus,HQStatus,approvedforsite,Salutation,FirstName,LastName,Website,Company,ABN_ACNNumber,Phone,Mobile,Notes,Description",
"'{$this->data['tradingname']}',
'{$this->data['street']}',
'{$this->data['suburb']}',
'{$this->data['state']}',
'{$this->data['postcode']}',
'{$this->data['category']}',
'{$this->data['subcategory']}',
'{$this->data['membership']}',
'{$this->data['salestatus']}',
'{$this->data['managerstatus']}',
'{$this->data['hqstatus']}',
'{$this->data['publishtoweb']}',
'{$this->data['title']}',
'{$this->data['firstname']}',
'{$this->data['lastname']}',
'{$this->data['webaddress']}',
'{$this->data['companyname']}',
'{$this->data['abnacn']}',
'{$this->data['phonenumber']}',
'{$this->data['mobile']}',
'{$this->data['notes']}',
'{$this->data['businessdescription']}'
");
break;
}
}
You need to do it in your script handle database fields and values by applying conditions. and make strings of both according to different user types before applying them in $this->insert function.
Something like below:
if($usertype=='yourtype')
{
$fieldsstr="TradingName,Street,City.................";
$valuestr=$this->data['tradingname'].",".$this->data['field2'].",".......
}
else
$fieldsstr="TradingName,Street.................";
$valuestr=$this->data['tradingname'].",".$this->data['field2'].",".......
}
$this->insert("customer_detail",$fieldsstr,$valuestr);

Categories