I have the following table and I am trying to display the sum of p_total along with all other records in the table. I have managed to display the total amount but if I display it, only values of the fist row of the table shows up. Although the sum of p_total is showing correctly as 600 .
Could you please tell me where is the problem in my code below:
Thanks in advance :)
My DB Table:
p_id p_name p_quantity p_rate p_total user_id
1 Pepsi 12 30 360 1
2 Hot Breads 12 20 240 1
I have the following code in my model
$this->db->select('*,SUM(temporary_table.p_total AS Total');
$this->db->from('temporary_table');
$this->db->where('user_id',$user_id);
$getData = $this->db->get('');
if($getData->num_rows() > 0) {
return $getData->result_array();
}
else {
return null;
}
This is my controller:
$this->load->model('mod_sales');
$data['records']= $this->mod_sales->add_to_temporary_table($user_id);
My View:
foreach ($records as $row)
{
<td><?php echo $row['p_name'];?></td>
<td><?php echo $row['p_quantity'];?></td>
<td><?php echo $row['p_rate'];?></td>
<td><?php echo $row['p_total'];?></td>
}
<?php echo $row['Total'];?>
You have a total and separate list.
$this->db->select_sum('total_price');
$this->db->from('order');
$this->db->where('dates BETWEEN DATE_ADD(NOW(), INTERVAL -7 DAY) AND NOW() ');
$query=$this->db->get();
$data['total']=$query->row()->total_price;
$this->db->select('*');
$this->db->from('order');
$this->db->where('dates BETWEEN DATE_ADD(NOW(), INTERVAL -7 DAY) AND NOW()');
$query=$this->db->get();
$data['count']=$query->num_rows();
Output:
Array (
[total] => 2759
[count] => 5
)
In your View:
$total_sum=0;
foreach ($records as $row){
<td><?php echo $row['p_name'];?></td>
<td><?php echo $row['p_quantity'];?></td>
<td><?php echo $row['p_rate'];?></td>
<td><?php echo $row['p_total'];?></td>
$total_sum+=$row['p_total'];
}
<?php echo $total_sum;?>
You're missing GROUP BY clause.
As I understand, you want this:
SELECT *, SUM(p_total) FROM temporary_table WHERE user_id = ... GROUP BY p_id
Not familiar with CodeIgniter, but guessing you need this line after "where":
$this->db->group_by('p_id');
Related
Table A
id
fullname
branch_code
Table B
id
branch_code
branch_name
I want to show list Table A with their branch name
here is the relation in table A
public function Branch () {
return $this->belongsTo('App\Model\Branch','branch_code','branch_code');
}
here is the controller
$TableA= TableA::orderBy('created_at','ASC')->get();
here is my blade
#foreach($TableAas $data)
<tr>
<td>{{ $i }}</td>
<td>{{$data->fullname}}</td>
<td>{{$data->Branch->branch_name}}</td>
</tr>
#endforeach
actually it works. but when i debug, i saw many duplicate queries like this
select top 1 * from [users] where [users].[branch_code] = '1001'
select top 1 * from [users] where [users].[branch_code] = '1002'
39.46ms
view::index:267
is there any way to make the query more simple and fast?
thank u
use with to load relation
$TableA= TableA::with('Branch')->orderBy('created_at','ASC')->get();
check EagerLoading problem and N+1 problem
I currently have a query that sums the number of non-active users in the last year and groups them by country and city and then paginates the result:
UserData::query()
->select(
country,
city,
DB::raw('SUM(CASE WHEN end_date IS NULL THEN 0 ELSE 1 END) AS not_active'),
)
->whereBetween('created_at', [Carbon::now()->subYear(), Carbon::now()])
->groupBy('country', 'city')
->paginate('500');
But I also need to add to each group a column that shows how many active users are of the same group, of all time, not just last year:
UserData::query()
->select(
country,
city,
DB::raw('SUM(CASE WHEN end_date IS NULL THEN 1 ELSE 0 END) AS active'),
)
->groupBy('country', 'city')
->get();
Then in the frontend I want to display the data in a table so I want the data to be "merged" so that I can output the matching active and not_active columns together, so the end result should look like that:
country | city | active(all time) | not active(past year)
------------|-----------|------------------|-----------------------
Sweden | Stockholm | 25 | 1
Switzerland | Bern | 43 | 13
But how can it be done when using pagination?
I tried to do it with subqueries but that didn't work: (Note that I am using slightly different query checking whereNull for active users and whereNotNull for non-active users:
$result = UserData::select('end_date', 'country', 'city')
->where(function ($query) {
$query->select('end_date')
->whereNull('end_date')
->whereBetween('created_at', [Carbon::now()->subYear(), Carbon::now()]);
}, 'active')
->where(function ($query) {
$query->select('end_date')
->whereNotNull('end_date')
}, 'not_active')
->groupBy('country', 'city')
->paginate('500');
This can be solved by using a union()
$first = UserData::query()
->select(
'country',
'city',
DB::raw('SUM(CASE WHEN end_date IS NULL THEN 0 ELSE 1 END) AS not_active'),
)
->whereBetween('created_at', [now()->subYear(), now()]);
$second = UserData::query()
->select(
'country',
'city',
DB::raw('SUM(CASE WHEN end_date IS NULL THEN 1 ELSE 0 END) AS active'),
);
$first->union($second)
->groupBy('country', 'city')
->paginate('500');
Which will execute a SQL union query like select *cols* from *table* where *clause* union (select *cols* from *table* where *someOtherClause*)
Table
--------------------------------------------------
user_id amount_unit
--------------------------------------------------
82ei3j3r2ijwkjewk32893e 3
2y8r42t8f432929420234y8 2
2y8r42t8f432929420234y8 4
82ei3j3r2ijwkjewk32893e 2
--------------------------------------------------
Result
--------------------------------------------------
user_id amount_unit
--------------------------------------------------
82ei3j3r2ijwkjewk32893e 5
2y8r42t8f432929420234y8 6
--------------------------------------------------
I also want to display user_id. I tried on the controller to only display the sum of amount_unit,
$data = BankDeposit::with('user')->selectRaw('SUM(amount_unit) as au')
->groupBy('user_id')->get();
foreach ($data as $value) {
echo $value;
}
You should pass the user_id to selectRaw() too.
$data = BankDeposit::with('user')->selectRaw('SUM(amount_unit) as au, user_id')
->groupBy('user_id')->get();
i'm having a problem with batch update function with codeigniter, i'm using a joining table for my products and categories, as I have a many to many relationship. I have searched high and low for an answer but still nothing so i have come here to ask more senior technicians for help.
I have 2 columns in a table "product_category" with "product_id" & "category_id" so I can link 1 product to many categories. I have managed to perform the insert query which inserts all the id's fine, but the update is not working. Here's my code:
model:
function update_product_cat($product, $cat_id) {
$data = array();
foreach( $product as $index => $value )
{
$data[] = array(
'product_id' => $value ,
'category_id' => $cat_id[ $index ]
);
}
$this->db->update_batch('product_category', $data,
'product_id');
}
array:
Array ( [0] => Array ( [product_id] => 327 [category_id] => 3 ) [1] => Array ( [product_id] => 327 [category_id] => 5 ) [2] => Array ( [product_id] => 327 [category_id] => 7 ))
My error code:
Error Number: 1062
Duplicate entry '327-3' for key 'PRIMARY'
UPDATE product_category SET category_id = CASE WHEN product_id = '327' THEN '3' WHEN product_id = '327' THEN '5' WHEN product_id = '327' THEN '7' ELSE category_id END WHERE product_id IN ('327','327','327')
Any help would be greatly appreciated:
thanks
I'm not 100% sure this is your entire problem, but it looks like the product_category table has product_id set as a primary key - where it looks like you are trying to enter many identical product_id's. If that were the case you should probably just be using a regular update not batch, not to mention removing/replacing the primary key.
Instead of doing never end copy past between 2 joomla 2.5 website (I want to copy past their modul and articles)
Phpmyadmin :
How can I copy past a single or multiple row (article, module) from one jrm_content to jasso_content (they have both exactly the same colons type)
I know how to select rows and to import them, but after...? (I changed the id are different exept for some the Asset ID is it a problem?
Thanks a lot!
What's wrong with queries like this?
INSERT INTO tableNew
(col1,col2,col3,col4,col5)
(
SELECT
col1,col2,col3,col4,col5
FROM tableOld
)
select from tablename where table name.primary key = table name.foreign key
<?php
$sname=$_POST['srname'];
$link=mysql_connect("localhost","root","") or die("Cannot Connect to the database!");
mysql_select_db("human_resource",$link) or die ("Cannot select the database!");
$query="SELECT * FROM employee WHERE fname='$sname'";
$resource=mysql_query($query,$link);
echo "
<table align=\"center\" border=\"1\">
<tr>
<td><b>FName</b></td> <td><b>lname</b></td><td><b></b></td><td><b>Department</b></td></tr> ";
while($result=mysql_fetch_array($resource))
{
echo "<tr><td>".$result[1]."</td><td>".$result[2]."</td><td>".$result[3]."</td></tr>";
}
echo "</table>";
?>