Codeigniter : retrieve lastest row in table? - mysql

table name : mytable
id name salt value
1 a 10 39
2 a 20 13
3 a 10 14
4 b 40 39
mymodel.php
function get_value_by_name($name)
{
$this->db->select("*");
$this->db->from("mytable");
$this->db->where('salt', '10');
$this->db->where('name', $name);
$this->db->order_by('id',"ASC");
$this->db->limit(1);
$query=$this->db->get();
if($query != null){
return $query->result();
}
else{
return array();
}
}
I want to get latest row with name= a and salt=10 (row with id = 3). But my current code return 1st row.

Change
$this->db->order_by('id',"ASC");
By
$this->db->order_by('id',"DESC");

Related

Laravel orWhereIn and orWhereIn and so on

To be honest I rly do not know how to describe my query problem, hope example will clear things up:
I've got simple query:
return $query->whereHas('categories', function ($q) use ($ids) {
$q->whereIn('category_id', $ids);
}, '=', count($ids));
which returns records that match array of categories ids. To present this better right now we've got such condition
getRecordsThatMatchThisCondition(id1 && id2 && id3... and so on).
What I want is to achieve such comparasion
getRecordsThatMatchThisCondition((id1.1 || id1.2 || id1.3) && (id2.1 || id2.2) ... and so on.)
I've couldn't find any help with this problem so far. Even naming such query would be helpfull. My table is simple PIVOT
id record_id category_id
------------------------------------
1 1 35
2 2 41
3 2 74
4 3 74
5 3 40
6 4 40
Summarizing my problem with words:
I do not have record relation to parent_category of selected category... Right now I need to display all records that match multiple categories.
Visualising problem:
Record is assigned to categories like this:
35
└40
└41 ☑
36
└74 ☑
By providing id 35 and 36, record should be found! By providing 40, 74 should NOT be found...
Hope I've described my problem well enough.
You can't query with whereIn method like this, but can use a foreach loop, like this :
return $query->whereHas('categories', function ($q) use ($ids) {
foreach($ids as $key => $value) {
$q->orWhere('category_id', $value)
}
}, '=', count($ids));
Or, with for loop :
return $query->whereHas('categories', function ($q) use ($ids) {
for ($i = 0; $i < count($ids); $i++){
$q->orWhere('category_id', $ids[$i]);
}
}, '=', count($ids));

How do I count multiple columns with a vertical value?

I'm new to programing. I have table
check_1,check_2,check_3 ..etc
------------------------------
1 1 1
0 0 1
1 0 1
And I want this output :
column_name, count_true
-----------------------
check_1 2
check_2 1
check_3 3
I've tried it with mysql using the union function, but when I try to apply it in laravel I have trouble with union. Is there a unionless query that can produce such output?
Thanks in advance
You can do this way. One query in db
$records = DB::table('your_table')->get();
$check1Count = $records->where('check_1', 1)->count();
$check2Count = $records->where('check_2', 1)->count();
$check3Count = $records->where('check_3', 1)->count();
......
Or
$records = DB::table('your_table')->get();
$columns = ['check_1', 'check_2', 'check_3', ...];
$data = [];
foreach($columns as $column) {
$data[] = [
'column_name' => $column,
'count_true' => $records->where($column, 1)->count();
];
}
Also you can do this way but it is many query
$check1Count = DB::table('your_table')
->selectRaw('COUNT(check_1) as count')
->where('check_1', 1)
->first()
->count;
$check2Count = DB::table('your_table')
->selectRaw('COUNT(check_2) as count')
->where('check_2', 1)
->first()
->count;
.....
A normalised approach might look like this:
response_id checkbox
1 1
1 2
1 3
2 3
3 1
3 3
You don't need union, just query all the data and process it on Laravel. Let say you query all the data using eloquent to $data variable, then you should do it like this:
//preparing a variable to hold all 24 database field value
$total = [];
foreach ($data as $d) {
//do this for all 24 database field
if ($d->check_1) {
$total[1]++;
}
if ($d->check_2) {
$total[2]++;
}
...
}
By using that way you can't check the resutl on $total[index] variable. And yes, there is a better way to store your data instead of saving all the field for each user. You can just store all checked value in database that look like this :
user_id checkbox_id
1 3
1 5
1 9
1 24
2 23
3 2
3 3
It more efficient since you don't need to save the unchecked checkbox value, if they more likely not to checked most of the checkbox.

How to get the all child rows recursively using CodeIgniter and MySQL?

How to get the all child rows and their child rows using CodeIgniter and MySQL?
Here is the Table structure
Id user_id sponser_id
1 1 0
2 2 1
3 3 1
4 4 1
5 5 2
6 6 2
7 7 2
8 8 3
9 8 3
10 10 4
I want to get all the child row which is connected under particular sponser_id. I have trid this query but I can't get proper detail.
$this->db->select('u_fname,u_lname,sponsor_id');
$this->db->from('user_reg');
$this->db->where('sponsor_id', $user_data['otc_id']);
$query = $this->db->get();
Here is the graphical representation of what i am doing. I want all children row of A and same as b to O.
I am calling this function from my controller to get the desired output.
Controller Code:
public function index()
{
$all_level_array = array();
$user_data = $this->common->user_data_db();
$get_user_level = $this->u_buildup_wallet_model->get_user_buildup_level($user_data['otc_id']);
if(!empty($get_user_level)){
foreach ($get_user_level as $userData) {
$test = $this->u_buildup_wallet_model->get_user_buildup_level($userData['otc_id']);
print_r($test);
}
}
print_r($all_level_array);
exit
$this->load->view();
}
Model Code:
public function get_user_buildup_level($user_otc)
{
$this->db->select('u_fname,u_lname,sponsor_id,otc_id');
$this->db->from('user_reg');
$this->db->where('sponsor_id', $user_otc);
$query = $this->db->get();
$result = $query->result_array();
return $result;

Yii2 Update records resulting from query

I need to update month_no fields of the records resulting from a select query using some variables passed from controller but every field is written with the same value.
These are the variables:
$id_calc = 27
$from_y = "2013-05-01"
$to_y = "2015-11-31"
The table result:
id id_paid year_ref month_no
1 26 2012 12
2 26 2013 12
4 27 2013 12 (should be 8)
5 27 2014 12
6 27 2015 12 (should be 11)
This is model:
public function CorrectTable($id_calc, $from_y, $to_y)
{
$connection = Yii::$app->db;
$query = "SELECT * FROM my_table where id_paid='$id_calc'";
$data = $connection->createCommand($query)->queryAll();
// calculate no. of month first and last year
$month_no_begin = (13 - date("m",strtotime($from_y)));
$month_no_end = (date("m",strtotime($to_y)));
//
foreach($data as $row)
{
$id = $row['id'];
// calculate number of month per year
if ($row['year_ref'] = date("Y",strtotime($from_y)))
{
$month_no = $month_no_begin;
} elseif ($row['year_ref'] = date("Y",strtotime($to_y)))
{
$month_no = $month_no_end;
} else
{
$month_no = 12;
}
Yii::$app->db->createCommand()
->update('my_table', ['month_no' => $month_no], ['id' => $id])
->execute();
}
I tried to put the above code in controller with the same result.
A careless mistake once I had made before. You should use == or === in the if statement to test equal condition, instead of =
public function CorrectTable($id_calc, $from_y, $to_y)
{
$connection = Yii::$app->db;
$query = "SELECT * FROM my_table where id_paid='$id_calc'";
$data = $connection->createCommand($query)->queryAll();
// calculate no. of month first and last year
$month_no_begin = (13 - date("m",strtotime($from_y)));
$month_no_end = (date("m",strtotime($to_y)));
//
foreach($data as $row)
{
$id = $row['id'];
// use `==` instead of `=`
if ($row['year_ref'] == date("Y",strtotime($from_y)))
{
$month_no = $month_no_begin;
}
// use `==` instead of `=`
elseif ($row['year_ref'] == date("Y",strtotime($to_y)))
{
$month_no = $month_no_end;
}
else
{
$month_no = 12;
}
Yii::$app->db->createCommand()
->update('my_table', ['month_no' => $month_no], ['id' => $id])
->execute();
}
}
our if ... esleif ... else sequence seems not logig
as you done the else if is never executed
so you should change the condition this way the e
foreach($data as $row)
{
$id = $row['id'];
// assigne default value
$month_no = 12;
// check for month_begin
if ($row['year_ref'] == date("Y",strtotime($from_y)))
{
$month_no = $month_no_begin;
}
//check for month_end
if ($row['year_ref'] == date("Y",strtotime($to_y)))
{
$month_no = $month_no_end;
}
Yii::$app->db->createCommand()
->update('my_table', ['month_no' => $month_no], ['id' => $id])
->execute();
}

How can I transform a single column query output to a multi-column one?

I have SQL query that produced more than 1000 rows. How it can get as columns ?
Example:
1
2
...
999
1000
how can I get as,
1 101 ....
2 102
... ...
99 199
100 200
following code displays
1 2 3 ...100
101 102 103 ...200
I want like this
1 101
2 102
... ...
99 199
100 200
$result=mysql_query("SELECT * FROM master_break");
$display = 10;
$cols = 0;
echo "";
while($fetched = mysql_fetch_array($result)){
if($cols == 0){
echo "\n";
}
// put what you would like to display within each cell here
echo "".$fetched['sName']." | ".$fetched['value']."";
$cols++;
if($cols == $display){
echo "";
$cols = 0;
}
}
// added the following so it would display the correct html
if($cols != $display && $cols != 0){
$neededtds = $display - $cols;
for($i=0;$i\n";
echo "";
}
echo "";
} else {
echo "";
}
?>
This will more than likely need to be done in the presentation layer (or display of data). The query can not produce multiple columns from 1 column, so you will ned to display the data as you need it in your code.