I was trying to update my table but I couldn't make it work.. I always end up with the error:
Invalid argument supplied for foreach()
Here is my Controller:
public function show_score($id)
{
$scores = Score::with(['lead','subject'])->where(['subject_id'=>$id])->get();
return view('markbook.show_score',compact('scores'));
}
public function update_score(Request $request)
{
$id = $request->input('id');
$scores = Score::find($id);
foreach ($scores as $datas) {
$datas->jan_ap=$request->input('jan_ap');
$datas->jan_hm=$request->input('jan_hm');
$datas->save();
}
}
route:
Route::get('markbook/scores/{id}', 'MarkbookController#show_score' );
Route::post('markbook/scores', 'MarkbookController#update_score');
Here is my table I'm trying to loop the updated score:
From chat discussion what found is that you want to update multiple scores, which is listed in tr, td. You can change it like this
Change in view
#foreach($scores as $score)
<tr>
<td>{{$score->lead->student_name}} <input type="hidden" name="scores[{{$loop->index}}][id]" value="{{$score->id}}"></td>
<td><input type="text" name="scores[{{$loop->index}}][jan_ap]" value="{{$score->jan_ap}}"></td>
<td><input type="text" name="scores[{{$loop->index}}][jan_hm]" value="{{$score->jan_hm}}"></td>
</tr>
#endforeach
Controller update score
public function update_score(Request $request)
{
$scores = $request->input('scores'); //here scores is the input array param
foreach($scores as $row){
$score = Score::find($row['id']);
$score->jan_ap = $row['jan_ap'];
$score->jan_hm = $row['jan_hm'];
$score->save();
}
}
Using Score::find($id) you're only ever going to return 1 result so there won't be anything to foreach over.
If you just want to update a single row in the table you don't need to foreach it.
You can simply run
$score = Score::find($request->input($id));
$score->jan_ap = $request->input('jan_ap');
$score->jan_hm = $request->input('jan_hm');
$score->save();
if you want to return multiple rows you need to change your find to a get()
so $scores = Score::where('something', $request->input('something))->get();
If you want to update every row in the table with the same information you'd do a:
$scores = Score::all();
That would return every row in the table.
Related
I am new in codeigniter both php, I am beginner. Could anyone help me how to show a data from another table based on ID in each row in same View in codeigniter, i just include a file(that is a form with data from another table) im not sure.. how the method should be.. dont know what to do plz ! thx
CONTROLLER
$this->load->model('m_work_order');
$this->load->model('m_srv_product');
$data['items'] = $this->m_work_order->show_items()->result();
$id=0; // dont know what to do with this ID
$data1['record'] = $this->m_srv_product->show_data($id)->result_array();
$data['form'] = $this->load->view('work_order/form_file', $data1, TRUE);
$this->load->view('work_order/form_input',$data);
MODEL m_work_order
function show_items(){
$query = "SELECT *
FROM work_order_items
WHERE item_status='0'";
return $this->db->query($query);
}
MODEL m_srv_product
function show_data($id)
{
$query= "SELECT a.srv_pr_id,a.srv_vol,a.srv_n,
b.srv_name,c.prod_cat_name,c.prod_cat_id
FROM srv_pr_use as a,service as b, prod_category as c
WHERE a.srv_id = b.srv_id and
a.prod_cat_id = c.prod_cat_id and
a.srv_id = $id ";
return $this->db->query($query);
}
VIEW
foreach ($items as $t){
echo "
<tr>
<td>$no</td>
<td>$kode</td>
<td>$t->item_name</td>
<td>$t->item_qty</td>
<td>".$form."</td>
</tr>"
}
I need to calculate in a function the average score of a column named: "totalscore" from my database table "score"
I tried to do Active record select_avg() but I am not getting anything.
Any idea how I can do this?
function calculateaverage(){
$dataArr = array();
$data = $this->db->get('score');
$maxrows = $data->num_rows();
$data = $this->db->get('score');
for ($i = 1; $i<= $maxrows-1; $i++){
$this->db->select('totalscore');
foreach ($data->result() as $row) {
$dataArr[$i] = $row->totalscore;
}
}
return $dataArr;
}
You can try this code, very simple and straight forward. write it in your model. use in Controller like $this->yourmodel->calculateaverage;
basically we are telling codeigniter query builder to select the AVG of our totalscore..
function calculateaverage(){
$query = $this->db->select('AVG(totalscore) as average_score')->from('score')->get();
return $query->row()->average_score;
}
I have the following snippet in my code, but the problem is when i try to add multiple items. it is getting added but it is repalcing the previously added row , eg:- in the following code snippet only one record will be there for the id 150, and that record will be 13. can you please tell me what the problem is.
public function StoreSkills($skills,$id) {
$skills = "16,13";
$id = "150";
if(!empty($skills)){
$UserSkillsObj = ORM::factory('userskill');
$userskills = explode(',',$skills);
foreach($userskills as $skill)
{
// $UserSkillsObj = ORM::factory('userskill'); if this statement is here,
//records are getting added just fine.
$UserSkillsObj->user_id = $id;
$UserSkillsObj->skills_id = $skill;
$ids = $UserSkillsObj->save();
}
}
}
Move the line that creates the object to within your foreach loop. Having it outside means that you're always referencing the same object, therefore the final (second) loop saves over the first one, making it always 13.
Example:
foreach($userskills as $skill)
{
$UserSkillsObj = ORM::factory('userskill');
$UserSkillsObj->user_id = $id;
$UserSkillsObj->skills_id = $skill;
$ids = $UserSkillsObj->save();
}
I am trying to build a dynamic subnavigation with Codeigniter. I have managed successfully to build a dynamic main navigation, but can't seem to manage to loop through the data from the joined table. In my code below i know i am not using the Foreach for the submenu correctly, but can somebody please help me or at least point me in the right direction.
Thank you a lot in advance
I am loading the foreach loops in the view like so
foreach ($query->result() as $row) {
$page_menu = $row->page_menu;
$page_menuName = base_url().$row->url;
//If page_menu is in database 1, show main menu item
if ($page_menu == '1') {
echo anchor($page_menuName, $row->page_headline)."<br/>";
}
}
if ($page_id == $webpage_id)
{
// I WANT THIS PART TO LOOP. THIS IS DATA FROM THE JOIN TABLE
foreach ($query->result() as $row) {
echo $subpage_id. "<--SUBID- " .$webpage_id. "<--- webpage id- ".$subpage_headline. "<--subheadline <br/><br/>";
}
}
This is the controller:
$this->load->module('webpages');
$query = $this->webpages->get_where_custom('url', $first_bit);
foreach ($query->result() as $row) {
$data['id'] = $row->id;
$data['headline'] = $row->headline;
$data['url'] = $row->url;
$data['content'] = $row->content;
$data['page_menu'] = $row->menu;
$data['sub_id'] = $row->sub_id;
$data['webpage_id'] = $row->webpage_id;
$data['sub_headline'] = $row->sub_headline;
}
And this is the model:
function get_where_custom($col, $value) {
$table = $this->get_table();
$this->db->where($col, $value);
$this->db->join('subpages', 'subpages.webpage_id = webpages.id', 'left');
$query=$this->db->get($table);
return $query;
}
My tables:
webpages
id,
headline,
title,
url,
content,
page_menu
subpages
sub_id,
subpage_headline,
subpage_title,
subpage_url,
subpage_content,
webpage_id,
sub_headnav
Your code:
if ($page_id == $webpage_id)
is not inside your foreach loop, is one thing. I know you say "i know i am not using the Foreach for the submenu correctly" but it's really hard for us to help you if you don't fix the bits you already know about before posting. No idea if what I said above is your problem or not
I am working on a simple order system.
the peice of code I am stuck on is the following:
if (isset($_GET['cart']))
{
$cart = array();
$total = 0;
foreach ($_SESSION['cart'] as $id)
{
foreach ($items as $product)
{
if ($product['id'] == $id)
{
$cart[] = $product;
$total += $product['price'];
break;
}
}
}
include 'cart.html.php';
exit();
}
This is the code is build on a preset array. I am working with a table with a few columns in mysql.
I have decided on the following:
if (isset($_GET['cart']))
{
$cart = array();
$total = 0;
foreach ($_SESSION['cart'] as $id)
{
while($row = mysql_fetch_assoc($productsSql)) {
foreach ($row as $product)
{
if ($product['id'] == $id)
{
$cart[] = $product;
$total += $product['price'];
break;
}
}
}
include 'cart.html.php';
exit();
}}
To display this "cart" I have decided on this:
foreach ($cart as $item) {
$pageContent .= '
<tr>
<td>'.$item['desc'].'</td>
<td>
R'.number_format($item['price'], 2).'
</td>
</tr>
';
}
All this seems to do is produce my cart in a fashion where when viewed it displays a list of only the items' id, e.g. where the description and price are supposed to be, I only get the items id in both fields... I also get a total price of 0.
Can anyone spot where I am going wrong here?
Or atleast try to give me some input so that I get going in the right direction!
Thanks!!
$productsQuery = 'SELECT `id`, `refCode`, `desc`, `pack`, `measure`, `quantity`, `deptCode`, `taxable`, `price1`, `price2`, `crdCode`, `cost1`, `cost2` FROM `products` ORDER BY `desc` ';
$productsSql = mysql_query($productsQuery) or die(mysql_error());
if (mysql_num_rows($productsSql) == 0) {
die('No results.');
} else {
$orderContent = '';
while($row = mysql_fetch_assoc($productsSql)) {
$prId = $row['id'];
$prRefCode = $row['refCode'];
$prDesc = $row['desc'];
$prPack = $row['pack'];
$prMeasure = $row['measure'];
$prQuantity = $row['quantity'];
$prDeptCode = $row['deptCode'];
$prTaxable = $row['taxable'];
$prPrice1 = $row['price1'];
$prPrice2 = $row['price2'];
$prCrdCode = $row['crdCode'];
$prCost1 = $row['cost1'];
$prCost2 = $row['cost2'];
$orderContent .= '
<tr>
<td>'.$prId.'</td>
<td>'.$prDesc.'</td>
<td>'.$prPack.'x'.$prSize.' '.$prMeasure.'</td>
<td>R'.$prPrice1.'</td>
<td>
<form action="" method="post">
<div>
<input type="text" size="3" name="quantity" />
</div>
</form>
</td>
<td>
<form action="" method="post">
<div>
<input type="hidden" name="id" value="'.$prId.'" />
<input type="submit" name="action" value="Order" />
</div>
</form>
</td>
</tr>
';
}}
Let's say that each of the rows in your database looks like this...
[product_id][product_name][product_description][product_price]
When you assign your query return to a variable passed through mysql_fetch_assoc() using a while loop, each pass will isolate a whole row. Of which you can piece apart manually by array key reference ($array['product_id']) or by using a foreach loop. I think the problem you're having is that you are mixing this up. Keeping the above example table layout in mind, you could do something like the following:
while ($tableRow = mysql_fetch_assoc($query)) { // Loops 3 times if there are 3 returned rows... etc
foreach ($tableRow as $key => $value) { // Loops 4 times because there are 4 columns
echo $value;
echo $tableRow[$key]; // Same output as previous line
}
echo $tableRow['product_id']; // Echos 3 times each row's product_id value
}
Look at this line in your code: if ($product['id'] == $id) { }
I think you probably mean if ($row['id'] == $id) { } instead.
Your middle code block makes no sense. You loop over session variables, and run a query each time... but it's the SAME query, and using an undefined variable to boot. Looping over a result row doesn't make much sense, as you'd be looping over the individual fields that your query returns for each row.
e.g. If your products table has just (id, name, description) as fields, then $row would be an array that looks like:
$row = array('id' => xxx, 'name' => yyy, 'description' => zzz);
When you foreach() on $row(), you'd not getting individual products, you'd be getting those fields in the row. $product would be xxx, then yyy, then zzz.
I don't know what your code is trying to accomplish - I'd guess you're trying to retrieve prices for products that a user is adding into their cart, but you're going about it in a very strange and highly inefficient manner.