Suppose I have this native query on my model:
public function print_query($id){
$sql = "Select Field1,Field2,Field3.. FROM Table WHERE id = '".$id."' ";
if($this->db->query($sql, array($id))->num_rows() > 0)
{
return $this->db->query($sql, array($id))->result();
}
}
And this on my Controller:
public function emp_preview(){
$EmpID = $this->input->post('txt_id');
$data['p_det'] = $this->db_sal_details->print_query($EmpID);
$this->load->view('employee/preview',$data,TRUE);
}
And in my View: I wanted to display the values of Field1,Field2,Field3,and so on.,
I used this code to display them;
<table>
<tr>
<?php if($p_det):?>
<?php foreach($p_det as $det):?>
<th><?php echo $det->Field1;?></th>
<th><?php echo $det->Field2;?></th>
<th><?php echo $det->Field2;?></th>
...
<?php endforeach;?>
<?php endif;?>
</tr>
</table>
This is all work fine and display the field and its values. But what if i have more than just 3 fields (50 fields e.g) and I want to dynamically populate the TH with out typing each Fields. How can i do this.,?
I know it's very simple for you experts ,.but I'm just a beginner here.. please bear with me and help me with this one., Thanks in Advance for any replies..
I think you could use foreach to iterate through the property which contains Field1, Field2.etc of the object $det
Model
public function print_query($id){
$sql = "Select Field1,Field2,Field3.. FROM Table WHERE id = '".$id."' ";
if($this->db->query($sql, array($id))->num_rows() > 0)
{
return $this->db->query($sql, array($id));
}
}
View
<table>
<tr>
<?php if($p_det):?>
<?php foreach($p_det->result_array() as $det):?>
<?php foreach($det as $field => values){?>
<th><?php echo $columns[$field] = $values;?></th>
...
<?php
}
endforeach;
?>
<?php endif;?>
</tr>
</table>
Related
I want to fill in the table. The database is filling the array, but this method didn't work. What is the problem? How to use foreach loop?
<?php
$a = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.ustsayfaid");
$a->execute(array());
$b = $a->fetchALL(PDO::FETCH_ASSOC);
$c = $a->rowCount();
$q = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.altsayfaid");
$q->execute(array());
$w = $q->fetchALL(PDO::FETCH_ASSOC);
$e = $q->rowCount();
if($c){
foreach($b as $w and $m as $n){
?>
<tbody>
<tr>
<td>
<?php echo $m["sayfa_adi"];?>
</td>
<td>
<?php echo ($n["sayfa_adi"]);?>
</td>
</tr>
<?php
}
}
?>
</tbody>
Here's what I came out with.
<?php
$firstQuery = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.ustsayfaid");
$firstQuery->execute(array());
$firstQueryResults = $firstQuery->fetchALL(PDO::FETCH_ASSOC);
$firstQueryCount = $firstQuery->rowCount();
$secondQuery = $db->prepare("select *
from sabit_sayfalar
inner join alt_sayfa on sabit_sayfalar.sayfa_id = alt_sayfa.altsayfaid");
$secondQuery->execute(array());
$secondQueryResults = $secondQuery->fetchALL(PDO::FETCH_ASSOC);
$secondQueryCount = $secondQuery->rowCount();
if ($firstQueryCount > 0 && $secondQueryCount > 0) {
?>
<tbody>
<?php foreach ($firstQueryResults as $firstQueryKey => $firstQueryRow) { ?>
<tr>
<td>
<?php echo $firstQueryRow["sayfa_adi"];?>
</td>
<td>
<?php echo ($secondQueryResults[$firstQueryKey]["sayfa_adi"]);?>
</td>
</tr>
<?php
}
}
?>
</tbody>
I changed the names of the variables for readability, and I adapted the table for using the information you provided... there are still some flaws connected with indexes that might be different for each SELECT, but that is another problem.
I also interpreted some variables that were missing as the variables you had but, for some reason, wrote wrong.
you cannot be used and in a foreach i think you want to use 2 foreach here and your <tbody> should be out of the loop
How to retrieve student scores on each subject from database table infront of their names..
My Model
public function getscore($class, $term, $session)
{
$query = $this->db->query("SELECT scores FROM allscores WHERE class ='$class' AND term ='$term' AND session ='$session' AND scores !=0");
return $query;
}
controller
public function showscores()
{
$class=$this->input->post('classes');
$term=$this->input->post('term');
$session=$this->input->post('session');
$data['query_scores'] = $this->model->getscore($class,$term, $session);
$this->load->view('scoresheet', $data);
}
view page
<table>
<tr>
<?php
foreach ($query_scores->result() as $row)
{
?>
<td><?php echo $row->scores; ?></td>
<?php
}
?>
</tr>
</table>
Note: student name is listed horizontally on the left side of d page, subject names is displayed vertically as the heading.
My challenge is to display the score o each subject under d subject name for each students.
Your assistance in this regard would be very appreciated.
public function getscore($class, $term, $session)
{
$query = $this->db->query("SELECT scores FROM allscores WHERE class ='$class' AND term ='$term' AND session ='$session' AND scores !=0");
return $query-result();
}
Use result() to format and show thing from database.
Use following table format to display subject names
<table>
<thead>
<tr>
<td> SUB1 </td> <td> SUB2 </td> <td> SUB3 </td>
</tr>
</thead>
Now use your code for Corresponding Content.
The exact PHP code for displaying the subject score will depend on your database structure. For more clarification, please share your database table structure.
try this.
Model:
note: change field name and query structure to match yours
normaly this will require a join but this is a basic example for you to get the idea
public function getscore($class, $term, $session){
$query = $this->db->query("SELECT scores,student_id ,student_name, subject_id,subject_name , FROM allscores WHERE class ='$class' AND term ='$term' AND session ='$session' AND scores !=0");
return $query;
}
Controller:
public function showscores(){
$class=$this->input->post('classes');
$term=$this->input->post('term');
$session=$this->input->post('session');
$data['query_scores'] = $this->model->getscore($class,$term, $session);
// create array to hold the new organized data;
$list = array();
// list['scores'] will hold the student scores;
// list['students'] = will hold the student names
// list['subjects'] = will hold the subjects names
// loop throught the result
foreach ($query_scores->result() as $row){
$list['scores'][$row->student_id][$row->subject_id] = $row->scores;
$list['students'][$row->student_id]= $row->student_name;
$list['subjects'][$row->subject_id]= $row->subject_name;
}
$this->load->view('scoresheet', $list);
}
view page:
<table>
<tr>
<?php
foreach ($subjects as $subject){
echo "<td>".$subject."</td>"; // will display subjects names on the first row
}
?> </tr> <?php
$column = 0;
foreach ($scores as $key=>$element){
echo "<tr>";
echo "<td>".$students[$key]."</td>"; // will display student names on the first col
foreach ($element as $subKey=>$subelement){
echo "<td>".$subelement."</td>";
}
echo "<tr>";
<?php
} ?>
</table>
Hey guys I need your help, I have this table
and I want to shows like this FIDDLE, really I don't know how to do this because sometimes just exist two columns(prov_name ) and sometimes exist more that two rows please help me if you can !
Hope you understand me. Thanks so much !
In this way I can be able to select data from Joomla.
$db =& JFactory::getDBO();
$query = 'SELECT prov_name FROM provprices where CA_id = '.$CA_id;
$db->setQuery($query);
$result = $db->loadObjectList();
$prov_name = $result[0];
echo $prov_name->prov_name;
First off, in order for your data to be presented like that obviously it must be grouped accordingly.
The first row is, the prov_name's, so you can use GROUP BY or you cal also do it in PHP. Based of the sample data, it should have from 1 to 6.
Then the second row is just a simple unitval and totval according to how many prov_name's.
Third is the and the rest is the grouping of the values. See Example:
$db = new PDO('mysql:host=localhost;dbname=DATABASE_NAME;charset=utf8', 'USERNAME', 'PASSWORD');
$data = array();
$results = $db->query("SELECT * from YOUR_TABLE_NAME");
while($row = $results->fetch(PDO::FETCH_ASSOC)) {
$data[$row['prov_name']][] = $row;
}
$keys = array_keys($data);
$size = count($keys);
$vals = array();
// grouping:
// if there are six (cam1 to cam6)
// then group them by cam1, ... to cam6, then repeat until theres no more left
while(count($data) > 0) {
foreach($keys as $key) {
if(!empty($data[$key])) {
$vals[] = array_shift($data[$key]);
} else {
unset($data[$key]); // remove them if empty
}
}
}
$vals = array_chunk($vals, $size); // split them by how many prov_names
?>
<table border="1" cellpadding="10">
<!-- PROV NAMES -->
<tr><?php for($x = 1; $x <= $size; $x++): ?>
<th colspan="2"><?php echo "prov_name $x"; ?></th>
<?php endfor; ?></tr>
<!-- unitval totvals -->
<tr><?php for($x = 1; $x <= $size; $x++): ?>
<td>unitval</td><td>totval</td>
<?php endfor; ?></tr>
<!-- the grouped values -->
<?php foreach($vals as $val): ?>
<tr>
<?php foreach($val as $v): ?>
<td><?php echo $v['unitval']; ?></td>
<td><?php echo $v['totval']; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>
I think you must do this first,
try looping to show prov_name in horizontal,
and then you fetch again in query with
"SELECT * FROM table_test where prov_name = '$prov_name'"
in Variable $prov_name you must have a value with CAM2 or CAM3 .etc
sorry just a logic :)
I'm in a class called database programming. We got a data set and and put it into our servers. Now I have to use a jquery plugin to help visualize that data. I am using Graph Us plugin and trying to use the "Fill In" option.
My professor helped me create this function:
<?php
include 'connect.php';
$country_query = "SELECT DISTINCT Country FROM FemaleMaleRatioNew";
$result = mysqli_query($sql_link, $country_query);
$new_row = array();
while ($row = mysqli_fetch_assoc($result)) {
$country = $row['Country'];
$query = sprintf("SELECT Year, Value FROM FemaleMaleRatioNew WHERE Country = '%s'", $country);
$country_result = mysqli_query($sql_link, $query);
while ($country_row = mysqli_fetch_assoc($country_result) ) {
$new_row[$country][] = array('year' => $country_row['Year'],
'value'=> $country_row['Value']
);
}
}
//print_r($new_row);
?>
the print_r($new_row); is only there to make sure it works and it does, it prints out the array when activated.
He then guided me to create the table like this:
<body>
<table id="demo">
<?php foreach($new_row as $row):?>
<tr>
<td><?=$row['year'];?></td>
<td><?=$row['country'];?></td>
</tr>
<?php endforeach;?>
</table>
<script type="text/javascript">
$(document).ready(function() {
// Here we're "graphing up" only the cells with the "data" class
$('#demo td').graphup({
// Define any options here
colorMap: 'heatmap',
painter: 'fill',
// ...
});
});
</script>
</body>
What else do I need to do to get the table to work? I can't seem to figure it out. All it does is come out blank.
I'm sorry if this question isn't worded correctly or if I have not been clear on anything please let me know.
You have multiple rows for each country in your $new_row variable. You have to iterate over countries first and then over the individual rows of data:
<?php foreach($new_row as $country => $rows): ?>
<?php foreach($rows as $row): ?>
<tr>
<td><?=$country;?></td>
<td><?=$row['Year'];?></td>
<td><?=$row['Value'];?></td>
</tr>
<?php endforeach;?>
<?php endforeach;?>
Also please note that you need colon ':' not semicolon ';' after the foreach statement. This syntax (which is less known) is described here: http://php.net/manual/en/control-structures.alternative-syntax.php
If you want to display some sort of aggregate (for example sum) per country and you want to calculate it in PHP (as opposed to MySQL) you can do it like this:
<?php foreach($new_row as $country => $rows):
$sum = 0;
foreach($rows as $row):
$sum += $row['Value'];
endforeach;
?>
<tr>
<td><?=$country;?></td>
<td><?=$sum;?></td>
</tr>
<?php endforeach;?>
You should be using a single JOINed query to do this stuff, but you may not have gotten that in class yet. Since it's homework, I won't give you the flat-out answer, but here's the pseudo-code:
$countries = SELECT DISTINCT Country FROM YourTable;
while($country_row = fetch_row($countries)) {
echo $country_row['Country'];
echo <table>;
$status = SELECT Year, Value FROM YourTable WHERE Country=$country_row['Country'];
while($stats_row = fetch_row($status) {
echo <tr><td>$stats_row['Year']</td><td>$stats_row['Value']}</td>
}
echo </table>
}
I am trying to create a website using codeigniter. I have two tables in the database. Theses tables are Category(Category Name, Category_Id) and Item(Item_Name, Category_id). Now, in my view I want of show the items in different tables for the different categories.
So far, I have come up with this, but obviously it is not working. The code in the model is this.
$query = 'select category_id as id, category_name as name from category;';
$result = $this->db->query($query);
$data['category'] = $result->result_array();
foreach($data['category'] as $d)
{
$query = "select item_name as name from item where item_catagory_id = '{$d['id']}';";
$result = $this->db->query($query);
$data["{$d['id']}"] = $result->result_array();
}
$this->load->view('view', $data);
The code in the view is like this.
<?php foreach($category as $c):?>
<h2><?php echo $c['name']; ?></h2>
<table>
<tr>
<td>Item Name</td>
</tr>
<?php foreach($c['id'] as $d): ?>
<tr>
<td><?php echo $d['name'];?></td>
</tr>
<?php endforeach;?>
</table>
<?php endforeach;?>
But it says that " Invalid argument supplied for foreach()". It also says that the error is in this line :
<?php foreach($c['id'] as $d): ?>
If I understand what you want to accomplish, Then here's what you want:
Change
$data["{$d['id']}"] = $result->result_array();
To:
$d['items'] = $result->result_array();
Then in your view, you'll simply do the second foreach like this:
<?php foreach($c['items'] as $d): ?>
This way you're adding the items to the category itself with a known key.