I wanted to check if the next TWO rows or ID is not NULL.
because if there is no succeeding TWO rows or ID then the income remains zero.
foreach ($data as $row)
{
if(($row->id + 2) != NULL) //I don't know what is the correct statement here
{
echo "<tr>";
echo "<td>".$row->id."</td>";
echo "<td>".$row->username."</td>";
echo "<td>"."650.00"."</td>";
echo "<td>".$row->remarks."</td>";
echo "<tr>";
}
else
{
echo "<tr>";
echo "<td>".$row->id."</td>";
echo "<td>".$row->username."</td>";
echo "<td>".$row->income."</td>";
echo "<td>".$row->remarks."</td>";
echo "<tr>";
}
}
Here is the table I want to achieve.
==================================
|ID | Username | Income | Remarks|
| 2 | user1 | 650.00 | |
| 3 | user2 | 650.00 | |
| 4 | user3 | 0.00 | |
| 5 | user4 | 0.00 | |
==================================
If I add a username then the next output will be this:
==================================
|ID | Username | Income | Remarks|
| 2 | user1 | 650.00 | |
| 3 | user2 | 650.00 | |
| 4 | user3 | 650.00 | |
| 5 | user4 | 0.00 | |
| 6 | user5 | 0.00 | |
==================================
You need to change your foreach to get the index.
foreach ($data as $index => $row)
Then you can address all rows relative to your current row with:
$row_two_ahead = $data[$index + 2];
you should check however if that row exists before you try to use it or you will get index out of range exceptions:
if (isset($data[$index + 2])) {
}
I solved the problem...
this is the code from my controller:
public function addUsername()
{
$data['id'] = NULL;
$data['username'] = $this->input->post('username');
$data['reward'] = 0.00;
$data['remarks'] = ' ';
$this->Matrix_model->addUsername($data);
$last = $this->Matrix_model->getLast();
$index = $last - 2; //I minus the last index with two
$this->Matrix_model->updateIncome($index); //and updated the income of that index
redirect('http://localhost/matrix/index.php/matrix');
}
and this is the code from my model:
public function addUsername($data)
{
$this->db->insert("income", $data);
}
public function getLast()
{
return $this->db->insert_id(); //this is the method to access the last id inserted
}
public function updateIncome($id)
{
$this->db->set("reward", 650);
$this->db->where("id", $id);
$this->db->update("income");
}
thank you and I'm sorry if other programmers didn't understand my questions
Related
So i have database table named usermeta and have table structure like this :
-----------------------------------------------------------
| ummeta_id | user_id | meta_key | meta_value |
-----------------------------------------------------------
| 1 | 1 | fullname | John Doe |
| 2 | 1 | birthplace | New York |
| 3 | 1 | birthdate | 1990/01/01 |
| 4 | 1 | mobile | 0812-3456-7890 |
| 5 | 1 | email | john.doe#mail.com |
| 6 | 2 | fullname | Jon Wick |
| 7 | 2 | birthplace | Washington DC |
| 8 | 2 | birthdate | 1985/10/21 |
| 9 | 2 | mobile | 0890-1234-5678 |
| 10 | 2 | email | wickjohn#mail.com |
And i try to generate json data for all data from this database using Codeigniter (v 3.1.9) using Controller and Model.
This is my Model (model name: db_usermeta)
function userslist()
{
$query = $this->db->select('*')
->from('usermeta')
->get();
return $query->result();
}
This is my Controller
public function userlist()
{
header('Content-Type: application/json; charset=utf-8');
$query = $this->db_usermeta->userslist();
$json_data = array();
foreach ($query as $key)
{
$json_data[$key->meta_key] = $key->meta_value;
}
echo json_encode($json_data);
}
The result when i open using my browser to check the json data using web developer tool is only show last record, in this case only show data from user_id 2, like this:
{
"fullname":"John Wick",
"birthplace":"Washinton DC",
"birthdate":"1985/10/21",
"mobile":"0890-1234-5678",
"email":"wickjohn#mail.com"
}
What I want to achieve is to show all json data nested like this:
"data": [
{
"fullname":"John Doe",
"birthplace":"New York",
"birthdate":"1990/01/01",
"mobile":"0812-3456-7890",
"email":"john.doe#mail.com"
},
{
"fullname":"John Wick",
"birthplace":"Washinton DC",
"birthdate":"1985/10/21",
"mobile":"0890-1234-5678",
"email":"wickjohn#mail.com"
}
]
How can i achieve this? Did I make a mistake on my controller and model. I really appreciate your help.
your $key->meta_key is overwriting for every record. that's why only last record appeared. You don't actually need to loop through to get json data.
public function userlist()
{
header('Content-Type: application/json; charset=utf-8');
$query = $this->db_usermeta->userslist();
$json_data = array(array());
$user_id_map = array();
$index = 0;
foreach ($query as $key)
{
if(!isset($user_id_map[$key->user_id])){
$user_id_map[$key->user_id] = $index++;
}
$currentIndex = $user_id_map[$key->user_id];
$json_data[$currentIndex][$key->meta_key] = $key->meta_value;
}
echo json_encode($json_data);
}
just change your controller code to this and this will return json data.
Since the meta key fullname is same for both records, you need to change the key name to something unique
foreach ($query as $key)
{
$json_data[$key->meta_key] = $key->meta_value;
}
Change $json_data[$key->meta_key] to $json_data[$key->meta_key.$key->user_id]
or simply change it to $json_data[$key->ummeta_id]
I have a table that contains Aspiring team for particular positions and various vote casted.
The data is below
Teamtable
| no | team | position | votes Cast |
| 1 | A | President | 2 |
| 3 | B | President | 1 |
| 4 | C | Secretary | 2 |
| 6 | D | Secretary | 1 |
I want to be able to get this in an html format using php and mysql just as below
EXPECTED VIEW IN THE HTML AND PHP FORMAT
PRESIDENT
Team | Total Votes | Percentage |
A | 2 | 66.67 |
B | 1 | 33.33 |
SECRETARY
Team | Total Votes | Percentage |
C | 2 | 66.67 |
D | 1 | 33.33 |
This is what i have tried so far
//QUERY
$SQL=SELECT
`team`,
`position`,
`votesCast`
FROM
Teamtable
$Results=$db->query($SQL);
$data=array();
while($row=mysqli_fetch_assoc($Results)){
$team=$row['team'];
$position=$row['position'];
$totalVote=$row['votesCast'];
$data[$position][]=$position;
$data1[$position][]=$team;
$data2[$position][]=$totalVote;
}
foreach($data as $position =>$electionResults){
$teams=$data1[$position];
$totalVotes=$data2[$position];
foreach($teams as $re => $teas){
$votes=$totalVotes[$re];
echo "
<table>
<tr>
<td>$teas</td>
<td>$votes</td>
</tr>
</table>";
}
}
I have to tried up to this point, any help is appreciated.
This could be very helpful for you
while($row = mysqli_fetch_assoc($result)) {
$data[$row['position']]['total'][]=$row['votes'];
$data[$row['position']][]=$row;
}
foreach($data as $k=>$v){
echo '<p>'.$k.'</p>';
echo '<table border="1">';
$total_votes=array_sum($v['total']);
foreach($v as $kk=>$vv){
if($kk!=='total'){
$percentage=round($vv['votes']/$total_votes*100,2);
echo '<tr><td>'.$vv['tean'].'</td><td>'.$vv['votes'].'</td><td>'.$percentage.'%</td></tr>';
}
}
echo '</table>';
}
You wan't to have the table on the outside of the foreach.
echo "<table>";
foreach($teams as $re => $teas){
$votes=$totalVotes[$re];
echo "<tr>
<td>$teas</td>
<td>$votes</td>
</tr>";
}
echo "</table>";
My Database table looks like this (rough outline):
+--------+-----------+-------------+---------+------------+------------+
| log_id | host_name | status | host_id | profile_id | event_date |
+--------+-----------+-------------+---------+------------+------------+
| 1 | site1 | Online | 2 | 1 | <*date*> |
+--------+-----------+-------------+---------+------------+------------+
| 2 | site1 | Online | 2 | 1 | <*date*> |
+--------+-----------+-------------+---------+------------+------------+
| 3 | site1 | Offline | 2 | 1 | <*date*> |
+--------+-----------+-------------+---------+------------+------------+
| 4 | site2 | Online | 4 | 1 | <*date*> |
+--------+-----------+-------------+---------+------------+------------+
| 5 | site2 | Maintenance | 4 | 1 | <*date*> |
+--------+-----------+-------------+---------+------------+------------+
Here are my codes:
VIEW:
<?php foreach($result as $row): ?>
['<?php echo $row->host_name;?>',<?php echo $this->help_model->filter_online($id,$row->host_id, 'Online');?>,
<?php echo $this->help_model->filter_online($id,$row->host_id, 'Offline');?>,
<?php echo $this->help_model->filter_online($id,$row->host_id,'Maintenance');?>],
<?php endforeach; ?>
CONTROLLER:
public function userreports()
{
$data['id']=$this->session->userdata('profile_id');
$this->session->set_userdata('from_date', '2015-01-01');
$from_date = $this->session->userdata('from_date');
$date = date('Y-m-d',now());
$this->session->set_userdata('to_date', $date);
$to_date = $this->session->userdata('to_date');
$data['result'] = $this->help_model->all_logs($this->session->userdata('profile_id'));
$this->load->view('squidtopus1-host-reports', $data);
}
MODEL:
function all_logs($id)
{
$id = $this->session->userdata('profile_id');
$this->db->select("*");
$this->db->from('server_log');
$this->db->where('profile_id',$id);
$query = $this->db->get()->result();
return $query;
}
function filter_online($data, $host_id, $status)
{
$from_date = $this->session->userdata('from_date');
$to_date = $this->session->userdata('to_date');
$id = $this->session->userdata('profile_id');
$this->db->select()->from('server_log');
$this->db->where('profile_id',$id);
$this->db->where('status',$status);
$this->db->where('host_id',$host_id);
$this->db->where('event_date >=',$from_date);
$this->db->where('event_date <=',$to_date);
$data = $this->db->get()->result();
$stat_count = 0;
foreach ($data as $row) {
$stat_count++;
}
return $stat_count;
}
The information that needs to displayed is shown properly, but the problem is that it repeatedly shows it for each row in the database that matches 'profile_id = $id'(in this case, profile_id=1).
Ideally it should show:
['site1', 2,1,0], ['site2', 1,0,1]
But instead it shows:
['site1', 2,1,0],['site1', 2,1,0],['site1', 2,1,0],['site2', 1,0,1],['site2', 1,0,1]
I can't determine where I've gone wrong... So any insight into solving this issue is greatly appreciated. Thanks ahead!
function all_logs($id)
{
$id = $this->session->userdata('profile_id');
$this->db->select("DISTINCT(host_id), host_name");
$this->db->from('server_log');
$this->db->where('profile_id',$id);
$query = $this->db->get()->result();
return $query;
}
try to change your function like above
Goal
I'm trying to draw up a restaurant menu in HTML using MySQL queries.
MySQL Tables
Categories
+-----------------------------------+
| id | nom_categorie | dimensions |
+-----------------------------------+
| 1 | pâtes | 1-2 |
| 2 | ailes de poulet | 3-4-5 |
+-----------------------------------+
Dimensions
+---------------------+
| id | dimension |
+---------------------+
| 1 | Petit |
| 2 | Gros |
| 3 | Unité |
| 4 | Repas (6) |
| 5 | Repas (12) |
+---------------------+
Repas
+-----------------------------------+
| id | repas | prix |
+-----------------------------------+
| 1 | spaghetti | 8.75,11.75 |
| 2 | lasagne | 9.95,13.25 |
| 3 | régulières | 0.95,9.50,11.95 |
| 4 | piquantes | 0.95,9.50,11.95 |
+-----------------------------------+
Desired outcome
+--------------------------------------+
| Pâtes |
+--------------------------------------+
| | petit | gros |
+--------------------------------------+
| spaghetti | 8.75 | 11.75 |
| lasagne | 9.95 | 13.25 |
+--------------------------------------+
+-----------------------------------------------+
| Ailes de poulet |
+-----------------------------------------------+
| | Unité | Repas (6) | Repas (12) |
+-----------------------------------------------+
| Régulières | 0.95 | 9.50 | 11.95 |
| Piquantes | 0.95 | 9.50 | 11.95 |
+-----------------------------------------------+
Current outcome
+--------------------------------------+
| Pâtes |
+--------------------------------------+
| | 1 | 2 |
+--------------------------------------+
| spaghetti | 8.75 | 11.75 |
| lasagne | 9.95 | 13.25 |
+--------------------------------------+
+--------------------------------------+
| Ailes de poulet |
+--------------------------------------+
| | 3 | 4 | 5 |
+--------------------------------------+
| Régulières | 0.95 | 9.50 | 11.95 |
| Piquantes | 0.95 | 9.50 | 11.95 |
+--------------------------------------+
Current code
function catalogue_complet($mysqli) {
$categories = mysqli_query($mysqli, "SELECT * FROM categories ORDER BY nom_categorie ASC");
$produits = mysqli_query($mysqli, "SELECT * FROM produits ORDER BY id, prix ASC");
$dimensions = mysqli_query($mysqli, "SELECT * FROM dimensions");
while($categorie = mysqli_fetch_array($categories))
{
echo "<h2>".$categorie[1]."</h2>";
echo "<table class='catalogue'>";
if(!empty($categorie[2]))
{
echo "<tr>";
echo "<th> </th>";
$array_categorie = explode("-",$categorie[2]);
foreach($array_categorie as $categorie)
{
echo "<th>".$categorie."</th>";
}
echo "</tr>";
}
while($produit = mysqli_fetch_array($produits))
{
if($categorie[0] == $produit[2])
{
echo "<tr>";
echo "<td>".$produit[1]."</td>";
$array_prix = explode(",",$produit[2]);
foreach($array_prix as $prix)
{
echo "<td class='prix'>".$prix."</td>";
}
echo "</tr>";
}
}
echo "</table>";
}
}
Other details
I may have a few errors slipped in with keys (example: $produit[2]) as I've simplified the tables, but I do have the proper information in my output. As I've mentioned above, my problem lies in the fact that I get the dimension ID as entered in my table repas. I can't figure out how to get the proper information (Ailes de poulet and Pâtes) to show up ?
I think you basically need to get the column names of your tables correctly.
In your current code, you are not using the dimensions table at all, although you have queried it.
Keep the names of all dimensions in an array, and refer them whenever the id is known.
Storing the dimensions in an array.
$dimensions = mysqli_query($mysqli, "SELECT * FROM dimensions");
$dim_arr = Array();
if($dimensions){
while($d = $mysqli_fetch_assoc($dimensions)){
$dim_arr[$d['id']] = $d['dimension'];
}
}else{
die(mysqli_error($mysqli));
}
Using them inside the foreach loop.
foreach($array_categorie as $categorie)
{
//Perform error checking here - if(isset($dim_arr[$categorie]))
$dim_name = $dim_arr[$categorie];
echo "<th>".$dim_name."</th>";
}
This should display the headings.
Ok, so I've found a working solution. Please excuse the length of the code, and as mentioned in the original post, some differences may occur when looking at the tables in the question, but it is simplified to focus on the desired effect.
Bottom line, the code below produces the table with title (ex: Pâtes), and each product and price line (ex: Lasagne | 9,95 | 13,25)
function catalogue_complet($mysqli) {
$categories = mysqli_query($mysqli, "SELECT * FROM catalogue_categories ORDER BY nom_categorie ASC");
$produits = mysqli_query($mysqli, "SELECT * FROM produits ORDER BY id, prix ASC");
$dimensions = mysqli_query($mysqli, "SELECT * FROM dimensions");
while($categorie = mysqli_fetch_array($categories))
{
echo "<h2>".$categorie[1]."</h2>";
echo "<table class='catalogue'>";
mysqli_data_seek($produits, 0);
if(empty($produits))
{
echo "<tr><td>".AUCUN_PRODUIT."</td></tr>";
}
else
{
while($produit = mysqli_fetch_array($produits))
{
// Dimensions -----------------------------------------------------------
if(!empty($categorie[3]))
{
echo "<tr>";
while($dimension = mysqli_fetch_array($dimensions))
{
$array_dimensions = explode("-",$categorie[3]);
foreach($array_dimensions as $dim)
{
if($dim == $dimension[0])
{
if($i == 0)
{
echo "<th> </th>";
}
echo "<th>".$dimension[1]."</th>";
$i++;
}
}
}
echo "</tr>";
}
// Produits -------------------------------------------------------------
if($categorie[0] == $produit[4])
{
echo "<tr>";
echo "<td>".$produit[1]."</td>";
$array_prix = explode(",",$produit[3]);
foreach($array_prix as $prix)
{
if( empty($prix) or ($prix == "0"))
{
echo "<td> </td>";
}
else
{
echo "<td class='prix'>".str_replace(".",",",$prix)." $</td>";
}
}
echo "</tr>";
}
}
}
echo "</table>";
}
}
This is my code
$Qemaster="select * from emaster where `branch`='$bid' and `department`='$did' and `status`!='L'";
$Remaster=mysql_query($Qemaster);
while($Rowemaster=mysql_fetch_array($Remaster)){
$empcode=$Rowemaster[id];
$name=$Rowemaster[name];
$Tleave=0;
echo "<tr>";
echo "<td rowspan='2'>".$name."</td>";
echo "<td>Leave</td>";
$Qlp="select `leave` from lpsummary where ((`month` IN(04,05,06,07,08,09,10,11,12) and `year`='$year') or (`month` IN(01,02,03) and `year`='$Nyear')) and `empcode`='$empcode'";
$Rlp=mysql_query($Qlp);
while($Rowlp=mysql_fetch_array($Rlp)){
$leave=$Rowlp['leave'];
$Tleave=$Tleave+$leave;
echo "<td>".$leave."</td>";
}
echo "<td><font color='red'>".$Tleave."</font></td>";
echo "<tr><td>Percentage</td>";
}
and my table is
------------------------------------------
| name | apr-12 | may-12 | jun-12 | jul-12 |
|------|--------|--------|--------|--------|
|Kumar | 2 | 1 | 0 | 3 |
|Rajan | 4 | 0 | 2 | |
| | | | | |
|------------------------------------------
Here under the name Rajan there is no data in jun-12 but jul-12 had the value 2...ie)empty row in the table lpsummary ...... if there is empty i wanna to replace it with as '-'... How can i do that by my code.....
In your while loop, you need to put a condition to check if a null from was returned.
while($Rowlp=mysql_fetch_array($Rlp)){
if (is_null($Rowlp['leave'])) {
$leave = '-';
} else {
$leave=$Rowlp['leave'];
$Tleave=$Tleave+$leave;
}
echo "<td>".$leave."</td>";
}