Code Igniter - remove single quotes from where_in - codeigniter

I have 2 queries:
$genres = $this->db->select('Group_Concat(intGenreId) strDJGenres')
->from('tblDJGenres')
->where('intDJId', $this->session->userdata('non_admin_userid'))
->get()
->row();
$results = $this->db->select('tblTracks.*, tblGenres.strName as strGenreName')
->from('tblTracks')
->join('tblGenres', 'tblTracks.intGenreId = tblGenres.intGenreId', 'left')
->where_in('tblTracks.intGenreId', $genres->strDJGenres)
->get()
->result();
The first query is returning a string such as
'1,2,3,4,8,6,5,7,45,66'
which I am using in my where_in clause on the second query. The issue is that with this string, it is writing the SQL like:
SELECT `tblTracks`.*, `tblGenres`.`strName` as strGenreName FROM (`tblTracks`) LEFT JOIN `tblGenres` ON `tblTracks`.`intGenreId` = `tblGenres`.`intGenreId` WHERE `tblTracks`.`intGenreId` IN ('1,2,3,4,8,6,5,7,45,66')
With the quote around it, it is treated as a single value. How can I get the second query to perform how I want it? ie
.... where `tblTracks`.`intGenreId` IN (1,2,3,4,8,6,5,7,45,66)

Multiple values can be passed to the where_in clause as an array.
The quotes from the start and end of the string can be removed using trim():
$dj_genres = trim($genres->strDJGenres, "'");
This string can then be converted into an array of strings, to pass to the where_in clause of the second query.
$dj_genres_array = explode(",", $dj_genres);
Or, if you need an array of integers:
$dj_genres_int_array = array_map('intval', $dj_genres_array);
You can just add the resultant array into the second query:
// ...
->where_in('tblTracks.intGenreId', $dj_genres_array)
// ...
Or:
// ...
->where_in('tblTracks.intGenreId', $dj_genres_int_array)
// ...

Answer given by the JLeft :
The quotes from the start and end of the string can be removed using the following function:
$dj_genres = trim($genres->strDJGenres, "'");
This string can then be converted into a array of strings, to pass to the where_in clause of the second query.
$dj_genres_array = explode(",", $dj_genres);
If you need an array on integers, it can be generated as so:
$dj_genres_int_array = array_map('intval', $dj_genres_array);
was working absolutely fine...Thanks JLeft

Related

don't want to write query every time while i want to calculation, how can i use variable?

$all_trades = FinalTrade::where('user_id', '=', $user_id)->where('market_id', '=', $market_id)->get();
I'm trying get all entries which has (col: buy_datetime > col: sell_datetime) and (col:buy_rate * quantities).
actually trying to get this in variable.
from $all_trades, how can store whole records of single column in variable?
for example, I want to store col: quantities into $abc varible.
Use pluck to get column from collection
$abc = $all_trades->pluck('quantities');
You can use where raw, this method allows you to write raw sql code for WHERE statement
FinalTrade::whereRaw('buy_datetime > sell_datetime')->get();
Or you can try to use Database Expressions
FinalTrade::where('buy_datetime', '>' DB::raw('sell_datetime'))->get();
For this column buy_rate * quantities you can use selectRaw method
FinalTrade::where('buy_datetime', '>' DB::raw('sell_datetime'))
->selectRaw('buy_rate * quantities as column1')
->get();
`$finalTrades = FinalTrade::get();
$numbers_of_entries = $finalTrades->count();
$finalTrades->transform(function (FinalTrade $finalTrade) use
($numbers_of_entries) {
$finalTrade->result = ($finalTrade->quantities * $finalTrade->buy_rate) /
$numbers_of_entries;
return $finalTrade;
});`

get all rows in single query with multiple id

I have a asset_request table with fields id and request_id.
I want to select multiple rows with specific ids.
$ids = $request->ids // 5,6
I want to select only rows with ids of 5 and 6 in request table
$ids = $request->ids;
$asset_request = asset_request::whereIn('id',array($ids))->first(); //gets only 6th row.
I need to get all rows matching the given ids.
To clarify after a chat discussion with the Op:
The Op was passing back a string request, therefore, the Op needed to change the following:
$id = $request->id;
$ids = str_split(str_replace(',', '', $id));
$asset_request = asset_request::whereIn('id', $ids)->get();
First you are calling the first method which will return only the first row matched.
You need to call get method to get all rows matched.
Secondly if you are sending ids as a comma separated string you need to convert it to array using explode.
$ids = $request->ids;
$asset_requst = asset_request::whereIn('id', explode(",", $ids))->get();
DB::table('asset_request')
->whereIn('id', (array) $request->ids)
->get();
or
TableModel::whereIn('id', (array) $request->ids)->get();

How to skip a row with file exists condition in laravel

This is for a search query based on many input fields, i'm doing if statements inside the query based on the inputs, for example :
$query = Model::all();
if($field = Input::get('field'))
$query->where('column_name', $field);
but what i want to do also is a condition to skip a row if there is no image with a name of that row id, like so :
if( file_exists('/img/'.$this_query->id) )
$query->skip();
Option 1: would be to make an array of the filenames, then utilize the whereIn query builder method, which checks for the occurrence of a column value in an array.
$query = Model::query();
$filenames = scandir('/img');
// the following excludes any id's not in the $filenames array
$query = $query->whereIn('id', $filenames);
Option 2: Run the query and then filter the resulting Collection in Laravel.
$query = Model::query();
// ... then build up your query
// the following gets the query results and then filters them out
$collection = $query->get()->filter( function($item) {
return file_exists('/img/'.$item->id);
}
Rationale: the database cannot check the filesystem during it's processing; so you either need to (Option 1) provide it a list from which to check, or (Option 2) do the checking after you get() the results back from the query.

_REQUEST only returning the first letter of input

I am trying to update records in a database through a form (post), but when I access the global parameter variables, only the first character of the original input is returned for some reason.
$conn->beginTransaction();
$sql = "UPDATE AS_PEOPLE SET pid=? WHERE name=?";
$stmt = $conn->prepare($sql);
$values = Array($_REQUEST['project'][0], $_REQUEST['person'][0]);
$stmt->execute($values);
$conn->commit();
echo "Ressource allocated<br>";
print_r($values);
Your problem is here
$values = Array($_REQUEST['project'][0], $_REQUEST['person'][0]);
$_REQUEST['project'] and $_REQUEST['person'] are strings, containing values of selected option. If you tell php to get the index of 0 of a string it returns the first letter only
$values = Array($_REQUEST['project'], $_REQUEST['person']);

Vtiger select query

I'm copying a vtiger query in a similar way but there is one change that the query given first having only one output so there is kept 0 in 2nd argument,
but in my customized query there are multiple outputs so what should I kept instead of 0
both are given as below:
original query
$is_recurring_event_query = $adb->pquery('SELECT recurring_group_id from vtiger_activity where activityid=?',array($id));
$is_recurring_event = $adb->query_result($is_recurring_event_query,0,'recurring_group_id');
copying it to use at different way
$is_recurring_event_activity_query = $adb->pquery('SELECT activityid from vtiger_activity where recurring_group_id='.$is_recurring_event);
$is_recurring_event_activity = $adb->query_result ($is_recurring_event_activity_query,0,'activityid');
You have to put variable and have to use for loop for your query to execute and get multiple values.
Suppose your query is like this
$result = $adb->pquery ('SELECT * from vtiger_activity where id='.$recordId);
$noofrow = $adb->num_rows($result );
for($i=0; $i<$noofrow ; $i++) {
$Data['activityid']=$adb->query_result($result,$i,'activityid');
$Data['activityname']=$adb->query_result($result,$i,'activityname');
}
Here in $Data you will get an array of the values.

Resources