I am trying to create a function that reads more easy any sql table no matter what number of columns.
class control_panel {
public function read_table($table_name, array $col_names) {
global $db;
$i = 0;
$result = $db->query("SELECT * FROM $table_name");
while($data = $result->fetch_object()) {
$i++;
foreach($col_names as $col_name) {
$cols[] = $data->$col_name;
}
}
var_dump($cols);
$nr_cols = count($cols);
/*for($j = 0; $j <= $nr_cols $j++) {
$cols[$j] =
}*/
}
}
$cp = new control_panel;
$col_names = array('ID', 'NewsTitle', 'NewsDescrption');
$cp->read_table('newss', $col_names);
Table structure:
ID NewsTitle NewsDescrption
1 title description
10 sda sd
Current output of the var_dump is:
array (size=6)
0 => string '1' (length=1)
1 => string 'title' (length=5)
2 => string 'descroierererer' (length=15)
3 => string '10' (length=2)
4 => string 'sda' (length=3)
5 => string 'sd' (length=2)
Expected output is to echo the table rows when I do $cp->read_table('newss', $col_names); in this way:
<tr>
<td>1</td>
<td>title</td>
<td>description</td>
</tr>
<tr>
<td>10</td>
<td>sda</td>
<td>sd</td>
</tr>
UPDATE change firts block of code to this as per David Jones answer.
public function read_table($table_name, array $col_names) {
global $db;
$results = array();
$result = $db->query("SELECT ".implode(',', $col_names)." FROM $table_name");
while($data = $result->fetch_object()) {
$results[] = $data;
}
foreach($results as $result) {
// how do I ouput dinamically here
//echo $result->$col_name...... this would lied to another array
}
}
Try this. You should only select the columns that you pass in rather than the whole table to limit un needed processing.
class control_panel {
public function read_table($table_name, array $col_names) {
global $db;
$results = array();
$result = $db->query("SELECT ".implode(',', $col_names)." FROM $table_name");
while($data = $result->fetch_object()) {
$results[] = $data;
}
return $results;
}
}
$cp = new control_panel;
$col_names = array('ID', 'NewsTitle', 'NewsDescrption');
$results = $cp->read_table('newss', $col_names);
$table = '';
foreach ($results as $item) {
$table .= '<tr>
<td>'.$item->ID.'</td>
<td>'.$item->NewsTitle.'</td>
<td>'.$item->NesDescription.'</td>
</tr>';
}
var_dump($table);
This should return an array of objects. Then you can access each column in a loop to show your table.
UPDATE:
You shouldn't loop through and generate your table inside the method as it is suppose to be generic and reusable. Instead return the results and loop in the controller or main PHP file.
Related
I might be punching slightly above my weight here or maybe its a really simple problem with a simple solution.
MY PROBLEM
I cant access array key values in foreach()
When creating the array in a function it seems that the array is duplicating, does a double iteration when created(as you can see in image below)
STEP 1: Array Creation
$results = $stmnt->fetchAll();
if ($stmnt->rowCount() > 0) {
$totalCorrectPicks = 0;
//--->HERE ARRAY KEYS ARE CREATED FROM QUERYING DB
foreach ($results as $index => $result) {
$returnResult = array('picked' => $result['team'], 'homeScore' => $result['homeScore'], 'awayScore' => $result['awayScore'], 'homeTeam' => $result['homeTeam'],
'awayTeam' => $result['awayTeam'], 'score' => $result['score']);
}//end foreach
//------> HERE ELEMENTS GETS APPENDED TO ARRAY
$pickedTeam = $result['team'];
if ($result['homeScore'] > $result['awayScore']) {
$matchOutcome = $result['homeTeam'];
$matchScore = $result['homeScore'];
$returnResults['matchOutcome'] = $matchOutcome;
$returnResults['matchScore'] = $matchScore;
}
if ($result['awayScore'] > $result['homeScore']) {
$matchOutcome = $result['awayTeam'];
$matchScore = $result['awayScore'];
$returnResults['matchOutcome'] = $matchOutcome;
$returnResults['matchScore'] = $matchScore;
}
if ($pickedTeam === $matchOutcome) {
$totalCorrectPicks++;
$margin = abs($matchScore - $result['points']);
//INDEX WILL START AT 0 SO WE ADD ONE TO $INDEX
$nrGames = $index + 1;
$returnResults['totatlCorrectPicks'] = $totalCorrectPicks;
$returnResults['margin'] = $margin;
$returnResults['nrGames'] = $nrGames;
}
elseif ($pickedTeam !== $matchOutcome) {
$margin = 'wrongPick';
$returnResults['margin'] = $margin;
}
}
}
if(isset($returnResults)){
print_r($returnResults);
return $returnResults;
}
return false;
}
STEP 2 Calling function and using array; leads to illegal string offset
<?php $picks = checkUserPicks('5');
foreach ($picks as $index => $pick){
?>
<tr>
<td>
<?php echo $pick['picked']; ?>
</td>
<td>
<?php echo $pick['matchOutcome']; ?>
</td>
<td>
<?php echo $pick['margin']; ?>
</td>
</tr>
<?php } ?>
NOTE: you can see the array value in the image posted above.
Questions
1) Why does it seem like the array is duplicated (see image)?
2) How can I fix the illegal string offset and what causes it?
Thanks
UPDATE
New Array Structure after removing [] from $returnResults[]
After end of foreach loop, matchOutcome, matchScore, etc are appended to the array. Shouldn't it be inside the loop?
If you are expecting more than one row, then you need to create array by maintaining its index as follows:
$returnResults = array(); // Initialize array
foreach ($results as $index => $result) {
$returnResults[$index] = array('picked' => $result['team'], 'homeScore' => $result['homeScore'],
'awayScore' => $result['awayScore'], 'homeTeam' => $result['homeTeam'],
'awayTeam' => $result['awayTeam'], 'score' => $result['score']);
//------> HERE ELEMENTS GETS APPENDED TO ARRAY
$pickedTeam = $result['team'];
if ($result['homeScore'] > $result['awayScore']) {
$matchOutcome = $result['homeTeam'];
$matchScore = $result['homeScore'];
$returnResults[$index]['matchOutcome'] = $matchOutcome;
$returnResults[$index]['matchScore'] = $matchScore;
}
.
.
elseif ($pickedTeam !== $matchOutcome) {
$margin = 'wrongPick';
$returnResults[$index]['margin'] = $margin;
}
}//end foreach
function practise()
{
$this->load->database();
$qry = mysql_query("select * from demmo");
if (mysql_num_rows($qry) > 0)
{
while ($row = mysql_fetch_array($qry))
{
$created = $row['created'];
//from here
$qry = mysql_query("select * from demmo where created = '$created'");
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
$users[] = array('user_id' => $user_id, 'name' => $name);
}
$dotts[] = array('created' => $created2);
//till here
}
return array ($dotts,$users);
}
}
in demmo table i am trying to fetch data and showing that data according to date .the problem is that the code is only selecting one date from the table from created rows and showing that data only .fortunately data shown is not only last but the data with actual date.
You need to create an array and use array_push to get more than one result. Right now your code is only returning the last result of the while loop:
For example, to get all of the dates:
$dotts = array();
$allusers = array();
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
array_push($dotts, $created2);
$users[] = array('user_id' => $user_id, 'name' => $name);
array_push($allusers, $users);
}
//
return array ($dotts,$allusers);
You need to create an array and use array_push function , then only it will have more than one value.
example:
create an empty array as
$allUser = array();
then after this line
$users[] = array('user_id' => $user_id, 'name' => $name);
use array_push as
array_push($allUser, $users);
}
return array($dots, $allUser);
I ma using codeigniter to generate some html options,but i only get one result,first result from the table.
This is my controller
public function edit_event($id = 0){
$id = $this->uri->segment(3);
$current_id = $this->ion_auth->get_user_id();
$data['data'] = $this->as->the_event_edit($id);
$data['groups'] = $this->as->the_groups_list($current_id);
$this->load->view('editevent',$data);
}
This is my model
public function the_groups_list($current_id){
$query = $this->db->get_where('all_groups', array('group_owner' => $current_id));
foreach ($query->result() as $row)
{
$data = array(
'group_title' => $row->group_title,
'group_name' => $row->group_name,
'group_owner' => $row->group_owner
);
return $data;
}
}
This is the other model
public function as_event_edit($id){
$query = $this->db->get_where('all_scheduled_messages', array('id' => $id));
foreach ($query->result() as $row)
{
$data = array(
'as_title' => $row->as_title,
'as_event_name' => $row->as_event_name,
'as_owner' => $row->as_owner,
'as_type' => $row->as_type,
'as_target_dataset' => $row->as_target_dataset,
'as_timestamp' => $row->as_timestamp,
'as_time' => $row->as_time,
'as_day' => $row->as_day
);
return $data;
}
}
I am then using $groups['group_title'] in view and only the first group title gets displayed even though i have like 4 group titles from the other rows.
How can i return and pass an array that i can then to the view so as to use foreach to iterate and display the group titles?.
In your model you're not creating a multi-dimensional array. You need to add keys either using a counter:
$data = array();
$i=0;
foreach ($query->result() as $row){
$data[$i]['as_title'] = $row->as_title;
$data[$i]['as_event_name'] = $row->as_event_name;
$data[$i]['as_owner'] = $row->as_owner;
$data[$i]['as_type'] = $row->as_type;
$data[$i]['as_target_dataset'] = $row->as_target_dataset;
$data[$i]['as_timestamp'] = $row->as_timestamp;
$data[$i]['as_time'] = $row->as_time;
$data[$i]['as_day'] = $row->as_day;
$i++;
);
return $data;
or use the key of the incoming array
$data = array();
foreach ($query->result() as $id => $row){
$data[$id]['as_title'] = $row->as_title;
$data[$id]['as_event_name'] = $row->as_event_name;
$data[$id]['as_owner'] = $row->as_owner;
$data[$id]['as_type'] = $row->as_type;
$data[$id]['as_target_dataset'] = $row->as_target_dataset;
$data[$id]['as_timestamp'] = $row->as_timestamp;
$data[$id]['as_time'] = $row->as_time;
$data[$id]['as_day'] = $row->as_day;
);
return $data;
Change the model from $data = to $data[] = to insert each row and not only one.
In your view loop over the groups, like so:
foreach ($data as $group) {
echo "Title" . $groups['group_title'];
}
RTM: Adding Dynamic Data to the View
In the controller: rename your $data['data'] to $data['event']
$data['event'] = $this->as->the_event_edit($id);
$data['groups'] = $this->as->the_groups_list($current_id);
$this->load->view('editevent',$data);
In your view:
foreach ($event as $items) {
var_dump($items);
}
foreach ($groups as $group) {
var_dump($group);
}
I have the following code:
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$result = $mysqli->query($query);
$rows = resultToArray($result);
//print_r($rows); // Array of rows
$result->free();
Brings back the following (only an excerpt):
Array ( [0] => Array ( [q17] => [COUNT(q17)] => 7 ) [1] => Array ( [q17] => Admin & Clerical [COUNT(q17)] => 118 )......etc.
What I am struggling with is how to then return the data, basically, what I need is some code to pull out the data as follows:
WHERE Array = Admin & Clerical BRING BACK THE COUNT(q17) number
How do I search through the array, normally, I'd use something like:
if($rows['q17']==$q[$i]){echo$rows['COUNT(q17)'];}
But this doesn't work - I assume because there are two sets of data within each part of the array? Not sure how to deal with this.
You can achieve this by using MYSQL itself, by using HAVING clause instead of WHERE.
To do this rewrite your query like this.
$query = 'SELECT q17, COUNT(q17) as qcount FROM tresults GROUP BY q17 HAVING q17="Admin & Clerical" ';
echo $row[0]['qcount']; //return 118
if you still want to it with PHP after getting the result from the database, it's how it done:
function get_q17_count($rows, $q17){
foreach ($rows as $onerow) {
if($onerow['q17'] == $q17){
return $onerow['COUNT(q17)'];
}
}
}
function resultToArray($results) {
$rows = array();
while($row = $results->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$querys = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$results = $mysqli->query($querys);
$rows = resultToArray($results);
//print_r($rows); // Array of rows
$results->free();
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['q17'] === $id) {
return $val['COUNT(q17)'];
}
}
return null;
}
Called the function using:
$id = searchForId($q[$i], $rows);echo " (".$id.")";
I have a table
Which I want show recursively like below picture
I am using a recursive function in php
function reccall($cat_id)
{
global $no,$recArray;
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['id'] = $row->id;
++$no;
reccall($row->id);
}
return $recArray;
}
but I am not able to generate a structured array like how the order is not the picture. A simple array is created all the time. Can anyone help me with creating the structured array like the order shown above.
<?
// I identified this function separately because it is performed only once, for preparing data
// It's collect an array of all parents in the correct order for each id
function dest($array) {
foreach($array as $key=>$value) {
if($value['pid']==0) continue;
$pid = $key;
$array[$key]['dest'] = array();
while ( $pid = $array[$pid]['pid'] ) {
if($key == $pid) exit("this tree is broken");
$array[$key]['dest'][] = $pid;
}
}
return $array;
}
// Recursive function that puts the items in the correct tree. removes the parameter dest.
function tree($array) {
foreach($array as $key=>$value) {
if( is_array($value['dest']) && !empty($value['dest']) ) {
$pid = array_pop($value['dest']);
if( empty($value['dest']) ) unset($value['dest']);
$array[$pid]['childrens'][$key] = $value;
$array[$pid]['childrens'] = tree($array[$pid]['childrens']);
unset($array[$key]);
}
}
return $array;
}
$array = array(
1 => array(
'title'=>'q',
'pid'=>0,
),
2 => array(
'title'=>'w',
'pid'=>1,
),
3 => array(
'title'=>'e',
'pid'=>0,
),
4 => array(
'title'=>'r',
'pid'=>2,
),
5 => array(
'title'=>'t',
'pid'=>1,
),
);
$tree = tree( dest($array) );
echo '<pre>';
print_r($array);
print_r($tree);
?>
By the way, I should note that these arrays are not very useful. Better to use the result of the function dest().
use this function instead of your function and your problem will be solved I hope
function reccall($cat_id)
{
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['main']['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['main']['id'] = $row->id;
$recArray[$no]['child'] = reccall($row->id);
++$no;
}
return $recArray;
}