Loop only iterating once inside function - php

I have the following function which should return all the tournaments and corresponding rounds inside an array.
When I call the function inside the body using a print_r I get only one tournament and round returned, however there are multiple tournaments and rounds. It is like the loop exits after only one iteration
function getTournaments(){
global $db;
$sql = "SELECT tournament, weekNum
FROM schedule
GROUP BY tournament";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$tournaments = $stmnt->fetchAll();
$data = array();
foreach($tournaments as $tournament){
$data = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
}//foreach
return $data;
}//function
print_r(getTournaments());
Database dump
Here you can see the corresponding mysql statement run on the db
My output / Problem
As you can see on image below I only get one tournament and round returned when doing print_r, why am I not getting all tournaments and rounds returned inside the function array? Am I missing something here?

you over write $data in the loop you want to create new arrays (multidimensional):
$data[] = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);

You should have used $data as an array :)
Use this
$data[] = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
instead of
$data = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);

Related

Recursive Function Result Not Ordered Correctly PHP

Good Day,
I am trying to get a correct ordered value from image above, I expect the value would be like below
2,3,4,5,6,7,8,19,9,20,10,11,12,13...18 (the order is from left top to right bottom)
I use this function below
function getUserEmptyLeg($sponsor_id){
$data_params = array(
":placement_id" => $sponsor_id,
":status" => "aktif"
);
$data = fetchAll("SELECT * FROM users WHERE placement_id =:placement_id AND STATUS=:status", $data_params);
$new_sponsor_ids = array();
$member = array();
foreach($data as $row){
$member[$row['user_id']] = array(
"placement_id" => $row['placement_id'],
"user_id" => $row['user_id'],
"member_name" => $row['username'],
"leg" => $row['leg']
);
$new_sponsor_ids[] = $row['user_id'];
}
foreach($new_sponsor_ids as $new_sponsor_id){
$member = array_merge($member, getUserEmptyLeg($new_sponsor_id));
}
return $member;
}
result from above function
2,3,4,5,8,9,10,11,12,13,14,...18,6,7,19,20
but the result from above function didn't output the result as i expected.
i am trying as best as possible to make my question clear, im sorry if you all confused when answering it. but i need help from you all, thanks.

Codeigniter - passing multiple value to view

I am trying to build a month report with Codeigniter.
i have problem in parse value to view,
when i enable profiler, i get 12 month query
Controller
$this->load->model('dash_model');
$data1= $this->dash_model->get_user_all();
$ind = $this->dash_model->monthreport();
$this->output->enable_profiler(TRUE);
$data = array(
'mont' => $ind,
'blok' => $data1
);
print_r($data);
$this->parser->parse('blank', $data);
the output print_r data
Array
(
[mont] => Array
(
[0] => stdClass Object
(
[trans_email] => 0
)
)
and dash_model
for($i=1; $i<=12;)
{
$month=array("","01","2","3","4","5","6","7","8","9","10","11","12");
$m = $month[$i];
$query2=$this->db->query("select count(*) as trans_email from trans_email where lup LIKE '2014-$m%' ");
$i++;
}
return $query2->result();
how i get output select count(*) as trans_email from trans_email where lup LIKE '2014-01%' and next month to view ?
like
month 1 = 356 data
month 2 = 2000 data and next
i'm trying this : Codeigniter - passing multiple values to view
but nothing happens
update
i'm trying to add this code into dash_model
$i++;
$resultarray[$i]=$query2->result();
}
return $resultarray;
and i got some error
* Object of class stdClass could not be converted to string*
okay dude let me try to guest :D
let's assume you use array on your view, i can assume that because you initialize $data with array.
First make sure you read this userguide
on result_array() section.
then change $query->result(); to $query->result_array();
then try to var_dump() it, hope it's work
just pass it as
$data['mont'] = $ind;
$data['blok'] = $data1;
$this->parser->parse('blank', $data);
in the view get the data as of $ind as $mont
and $data1 as $blok.
You could do
$data = array();
$data['mont'] = $ind;
$data['blok'] = $data1;
Instead of declaring it then initializing it at the same time. (It also allow you to add/change data in it whenever you want in your controller).
Then do debug($data);to see if you got everything you want in $data.

Associative array's loaded from database and display as 'columns'

I am trying to create an overview of product properties, for an invoice system.
So far, most things are comming together using classes and PDO.
I have the following issue.
In my class, i've created a function that builds my products array.
It loads some information from the database, to build this array.
This array, i want to use to display all the products i have selected:
$prod1 - $prod1Name - $prod1Descr - $prod1Price
$prod2 - $prod2name - $prod2Descr - $prod2Price
etc.
I figured that the Associative array would help me creating columns.
Though the problem is, that i do not understand a bit how to create multiple lines and columns this way.
I was thinking of something like:
$prod[1]["name"] - $prod[1]["descr"] - etc
Then to use this in a foreach loop to create as many new lines as required.
The only thing i could come up with is on my index.php (as shown below), cause using an index (the [1] defenition) does not seem to work the way i think it should be implemented.
For my understanding, i assigend the var in my class as an array, then redefine an array when loading the database information.
Could anyone tell me how i could try to solve this issue?
I have the following class:
<?
class Invoice{
var $vendorID;
var $product = array();
function product_array(){
global $db;
$query = $db->conn->prepare('
SELECT ProductName, ProductDescription, ProductDuration, ProductPriceInclVat, ProductPriceExclVat, ProductVatType
FROM products WHERE VendorID = :VendorID
');
$array = array (
'VendorID' => $this->vendorID
);
$query->execute($array);
$result = $query->fetchall();
if (empty($result)){
echo"Could not find any products matching your criteria.";
die;
} else {
foreach($result as $row) {
$this->product = array("Name" => $row['ProductName'],
"Description" => $row['ProductDescription'],
"Duration" => $row['ProductDuration'],
"PriceExclVat" => $row['ProductPriceExclVat'],
"PriceInclVat" => $row['ProductPriceInclVat'],
"VatType" => $row['ProductVatType']
);
}
}
}
}
?>
and then i have the following code on my index.php:
<?
$invoice = new Invoice();
foreach ($invoice->product as $key => $value){
echo $key . "<br>";
echo $value . "$value";
echo "<br>";
}
?>
When you are assigning the result arrays to the product property you are overwriting the array every time. You need to append to the array instead, so something like:
$this->product = array();
foreach($result as $row) {
$this->product[] = array(...);
}
Alternatively, you could just assign the results of fetchAll to the product property if you don't need to rename the field keys (or you could alias them in the SQL).
$query = $db->conn->prepare('
SELECT ProductName as Name,
ProductDescription as Description,
ProductDuration as Duration,
ProductPriceInclVat as PriceInclVat,
ProductPriceExclVat as PriceExclVat,
ProductVatType as VatType
FROM products WHERE VendorID = :VendorID
');
$array = array (
'VendorID' => $this->vendorID
);
$query->execute($array);
$product = $query->fetchall(PDO::FETCH_ASSOC);
The $product is now in the format you require.
After this you can avoid foreach loop in class invoice.
Other thing i noticed that you have made function product_array() which is not called,
so in index.php you are getting empty array (defined in class Invoice).
So in Invoice class it should be
$product = product_array()
and product_array function should return the value.

How to call function inside controller inside foreach loop with different parameters value

i am trying to call m custom function repeatedly with same or different parameters value,inside foreach loop parameters depending upon value to key provided my foreach.
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate=$this->getResult($username,$r->p_code);
print_r($toUpdate);
}
}
but when i am printing the latest query result i am getting $toUpdate get appended by latest parameter query.
Array
(
[query] => select * from `result` where (`studentid` = ?) and `studentid` = ? and `ccode` = ? and `a_no` = ? order by `date` desc limit 1
[bindings] => Array
(
[0] => XYZ
[1] => XYZ
[2] => course123code
[3] => 12321
)
[time] => 0.18
)
my user name getting same, while course code is get overrides while finding second result.
i want to get the result getResult() inside foreach loop so that it may give the related result for different parameters value.
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
This is a bad practice if you are fetching data from db inside the foreach loop.
BTW you can do this by keeping all new result in same array by index its some unique value, it will be look like this-
$toUpdate=array();
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate[$r->p_code]=$this->getResult($username,$r->p_code); // added $r->p_code as index to Array - $toUpdate
}
}
print_r($toUpdate); // this will give all the related result according your parameters
[UPDATE]
Try using unset($yourarray) for your next request these array will be new and they assign the new value each time -
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
unset($currentDetailOfUser);
unset($userdetail);
unset($condition_key);
unset($recentResult);
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
Hope this can help you.

$query->result_array() wipes away list_fields() data

I'm having an issue where I call the result_array() function on n query object from in codeigniter:
$this->db->select(array('a','b','c'));
$query = $this->db->get('basic');
print_r($query->list_fields());
$test = $query->result_array();
print_r($query->list_fields());
When I run this code, or:
$query = $this->db->get('basic');
print_r($query->list_fields());
print_r($query->list_fields());
or:
$query = $this->db->get('basic');
$test = $query->result_array();
print_r($query->list_fields());
The second list_fields() function always returns an array size 0, the first returns the correct list of field names.
In the last example where there is only one list_fields() function, the array is again size zero.
Any guidance in this matter will be greatly appreciated. I need the list_fields() function to be accessible after I read the result_array().
Here is the result of the first block of code:
Array
(
[0] => site_id
[1] => institution
[2] => caller
[3] => call_complete
[4] => call_details
[5] => id
[6] => timestamp
)
Array
(
)
Thank you, for your help
That looks to be a bug in the database driver. For example, in CI_DB_mysqli_result:
public function list_fields()
{
$field_names = array();
while ($field = $this->result_id->fetch_field())
{
$field_names[] = $field->name;
}
return $field_names;
}
A subsequent call will return array() because the while loop seeks over all the fields and leaves the pointer at the end of the list.
However, in the result class, result_id is public, so you can use mysqli_result::field_seek:
$query = $this->db->get('basic');
var_dump($query->list_fields());
// this should be called before any call to list_fields()
$query->result_id->field_seek(0);
var_dump($query->list_fields());
However, this is bad practise, as this only works for mysqli; for mysql, you'll need this:
mysql_field_seek($query->result_id, 0);
and for mssql:
mssql_field_seek($query->result_id, 0);
The correct way to do this is really to fix it in the database drivers. See this pull request :-)

Categories