Adding values of SQL count - php

I have a table which echos back some SQL counts for each user using foreach. I want to have a total which will add up all the counts foreach. Any ideas would be appreciated.
$students = get_course_students($course->id, 'lastname');
$toggle=0;
if (!empty($students)) {
foreach ($students as $student) {
$user=get_record('user','id',$student->id);
$atriskcountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_tutorial WHERE template = 2 AND user = $user->id AND course = $course->id");
$personalcountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_tutorial WHERE template = 1 AND user = $user->id AND course = $course->id");
$reportscountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_reports WHERE user = $user->id AND course = $course->id");
echo '<tr class="r'.$toggle.'">
<td class="cell c'.$toggle.'" valign="top" nowrap="true" align="left">'.fullname($user).'</td>
<td class="cell c'.$toggle.'" valign="top" align="center">'.$atriskcountrecords.'</td>
<td class="cell c'.$toggle.'" valign="top" align="center">'.$personalcountrecords.'</td>
<td class="cell c'.$toggle.'" valign="top" align="center">'.$reportscountrecords.'</td>
</tr>';
if($toggle==0)$toggle=1;
else $toggle=0;
}
}
echo'<tr>
<td><strong>Totals</strong></td>
<td align="center"><strong>(TOTAL)</strong></td>
<td align="center"><strong>(TOTAL)</strong></td>
<td align="center"><strong>(TOTAL)</strong></td>
<td></td>
</tr>';
echo'</table>';

If I really understand your question, it's quite easy ; just declare a variable per counter before your foreach loop and increase it with count value.
For example :
$atriskcountrecordsGlobal = 0;
if (!empty($students)) {
foreach ($students as $student) {
...
$atriskcountrecords = count_records_sql("SELECT COUNT(*) FROM mdl_ilp_tutorial WHERE template = 2 AND user = $user->id AND course = $course->id");
$atriskcountrecordsGlobal += $atriskcountrecords;
...
}

Related

validate if table row has data in every fields

I want to validate if a current row in every field has data on it and if it has not then display no data. Please help me. Also it is advisable to use echo in displaying the table data or should i stick to the html. Thanks in advance! I've been searching the net and was not able to find some answers. lol
$ct_list = mysqli_query($conn,"select * from ct LEFT JOIN station on ct.station_id=station.station_id LEFT JOIN dilg_emp on dilg_emp.station_id=station.station_id where dilg_emp.dilg_emp_id= $session_id");
if (mysqli_num_rows($ct_list) > 0){
while ($ct_row_list = mysqli_fetch_array($ct_list)) {
$ct_FName = $ct_row_list['ct_FName'];
$ct_MName = $ct_row_list['ct_MName'];
$ct_LName = $ct_row_list['ct_LName'];
$ct_SName = $ct_row_list['ct_SName'];
$ct_address = $ct_row_list['ct_address'];
$ct_birthday = $ct_row_list['ct_birthday'];
$ct_age = $ct_row_list['ct_age'];
$ct_gender = $ct_row_list['ct_gender'];
$ct_level_educ = $ct_row_list['ct_level_educ'];
$ct_course = $ct_row_list['ct_course'];
$ct_school = $ct_row_list['ct_school'];
$ct_prev_covid = $ct_row_list['ct_prev_covid'];
$ct_training_date = $ct_row_list['ct_training_date'];
$ct_deployment_date = $ct_row_list['ct_deployment_date'];
$ct_prev_emp = $ct_row_list['ct_prev_emp'];
echo "<tr>
<td>".
$x++."
</td>
<td>
$ct_FName $ct_MName $ct_LName $ct_SName
</td>
<td>
$ct_address
</td>
<td>
$ct_birthday
</td>
<td>
$ct_age
</td>
<td>
$ct_gender
</td>
<td>
$ct_level_educ
</td>
<td>
$ct_course
</td>
<td>
$ct_school
</td>
<td>
$ct_prev_covid
</td>
<td>
$ct_training_date
</td>
<td>
$ct_deployment_date
</td>
<td>
$ct_prev_emp
</td>
</tr>";
}
}else{
echo "<tr><td><b>Nothing to display</b></td></tr>";
}
You can loop over the row array, replacing empty values with No data.
$optional_fields = ["ct_SName"];
while ($ct_row_list = mysqli_fetch_array($ct_list)) {
foreach ($ct_row_list as $name => &$value) {
if (in_array($name, $optional_fields)) {
continue;
} elseif (empty($value)) {
$value = "No data";
}
}
// rest of your code goes here
It's hard to tell exactly what you mean, if a row has any empty columns then skip that row?
If you select 15 columns in the query or if you know that SELECT * will return 15 columns, then filter out the empty ones and see if there are 15:
if (mysqli_num_rows($ct_list) > 0) {
while ($ct_row_list = mysqli_fetch_array($ct_list)) {
if (count(array_filter($ct_row)) == 15) {
echo "<tr>
<td>$x++</td>
<td>$ct_FName $ct_MName $ct_LName $ct_SName</td>"; //etc...
}
}
}
You could also check and skip:
if (count(array_filter($ct_row)) < 15) {
continue;
}
//echo your HTML

Is there way to create foreach for sql code with array data

I got one query that takes data about users.
I need to make a 2nd query for each of these users.
I am getting data just for the first user. (with the second query)
First query:
$query = mysqli_query($conn, "SELECT * FROM tipuser WHERE permissions = '0'");
$ah = mysqli_fetch_array($query);
Also when i do for each($query as $x) and inside that i echo first and last name it shows all, when i do the same with $ah it doesn't show anything.
Then I got these variables:
$firstname = $ah['firstname'];
$lastname = $ah['lastname'];
Second query:
$sqlwork = mysqli_query($conn,
"SELECT DATE_FORMAT(datum, '%b %Y') AS Monthyear,
count(projekt) AS celkem,
SUM(projekt = 0) AS tipsport,
SUM(projekt = 1) AS slavia,
SUM(projekt = 2) AS bet
FROM zapasy
WHERE komentator1 = '$firstname $lastname'
OR komentator2 = '$firstname $lastname'
GROUP BY Monthyear");
I think the problem is somewhere in the array but I can't find it.
I am thankful for any help.
UPDATE:
this is how to display it on site:
<?php foreach($query AS $usersall) {?>
<table id="tablePreview" class="table table-hover table-sm table-bordered" style="border-top: 0px solid hsl(0, 0%, 87%);">
<thead style="color:black; background-color: hsla(0,0%,71%,1.00); border-top: 0px solid hsl(0, 0%, 87%);">
<tr>
<th scope="col">Měsíc</th>
<th scope="col">Zápasů</th>
<th scope="col">BET</th>
<th scope="col">TipSport</th>
<th scope="col">Slavia</th>
<th scope="col">Brutto</th>
<th scope="col">Daň</th>
<th scope="col">Netto</th>
<th scope="col">Zaplaceno</th>
</tr>
</thead>
<tbody>
<?php while ($tip = mysqli_fetch_assoc($sqlwork)) {?>
<tr>
<td>
<?=$tip['Monthyear'] ?>
</td>
<td>
<?=$tip['celkem']?>
</td>
<td>
<?=$tip['bet']?>
</td>
<td>
<?=$tip['tipsport']?>
</td>
<td>
<?=$tip['slavia']?>
</td>
<td>
<?php
$betx = $tip['bet']*$bet1cena['cena'];
$tipx = $tip['tipsport']*$tipcena['cena'];
$slax = $tip['slavia']*$slaviacena['cena'];
$celkem = $betx+$tipx+$slax;
echo "$celkem Kč";
?>
</td>
<td>
<?php
if($user['fakturuje'] == 0){
$dan = $celkem*0.15;
echo "$dan Kč";
}else{
echo "0 Kč";
}
?>
</td>
<td>
<?php
$netto = $celkem-$dan;
echo "$netto Kč";
?>
</td>
<td>
<input type="checkbox">
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php }?>
Although it is not completely clear from your question I think you are getting multiple rows from your first query and wanting to run the second query on each row returned by the first query
This is one way, I have taken the liberty of using a prepared query for the second one, this should remove any SQL Injection issues and also any problems with Last Names like O'Toole (the apostrophe issue). It also means you only need compile the query once, but can run it with new parameters as many times as you need.
$q1 = mysqli_query($conn, "SELECT * FROM tipuser WHERE permissions = '0'");
$q2 = "SELECT DATE_FORMAT(datum, '%b %Y') AS Monthyear,
count(projekt) AS celkem,
SUM(projekt = 0) AS tipsport,
SUM(projekt = 1) AS slavia,
SUM(projekt = 2) AS bet
FROM zapasy
WHERE komentator1 = ?
OR komentator2 = ?
GROUP BY Monthyear");
$stmt2 = $conn->prepare($q2);
while ($ah = mysqli_fetch_array($q1) ) {
// make the full name field
$name = $ah['firstname'] . ' ' . $ah['lastname'];
// bind those values to the prepared query
$stmt2->bind_param('ss', $name, $name );
$stmt2->execute();
// present the results of this query
// however you like
}

foreach loops giving unexpected results

I have a table of users and a table of scores in golf tournaments for those users. When a user plays a tournament he records a score in the results table using a form. I want to display a table of results showing the full list of users and the scores in the tournaments. There are eight columns of scores in the table - one for each course played. I am struggling with the php code to display the resulting scores. Where a player has played, his score appears correctly but if the following player in the table has not played his score is shown as the score for the player above him in the table. This continues down the list until a genuine score is encountered. I have tried to find the answer to this without success. Here is my code for just a single course. If I can overcome the problem for this I am sure the code will work for the other courses.
$query = "SELECT * FROM emg_users ORDER BY user_login";
$results=mysql_query($query);
$results_array = array();
while ($row = mysql_fetch_array($results)) {
$results_array[$row['ID']] = $row;
}
foreach ($results_array as $id => $record) {
$player = $record['user_login'];
?>
<tr>
<td class="padded_c" nowrap="nowrap"><?php echo $player;?></td> <!-- Player name -->
<?php
$query = "SELECT * FROM 0_tournament_test WHERE player = '".$player."' AND course = 'St_Andrews'";
$results=mysql_query($query);
$results_array = array();
while ($row = mysql_fetch_array($results)) {
$results_array[$row['id']] = $row;
}
foreach ($results_array as $id => $record) {
$pplayer = $record['player'];
if ($pplayer = $player) {
$sta = $record['score'];
}
else {
unset($sta);
}
$id++;
}
?>
<td class="padded_c" nowrap="nowrap"></td>
<td nowrap="nowrap"><?php echo $sta;?></td>
<td nowrap="nowrap"><?php echo $rsg;?></td>
<td nowrap="nowrap"><?php echo $bet;?></td>
<td nowrap="nowrap"><?php echo $oak;?></td>
<td nowrap="nowrap"><?php echo $kia;?></td>
<td nowrap="nowrap"><?php echo $cng;?></td>
<td nowrap="nowrap"><?php echo $mer;?></td>
<td nowrap="nowrap"><?php echo $oly;?></td>
<td nowrap="nowrap"><?php echo $allshots;?></td>
<td nowrap="nowrap"><?php echo $sss;?></td>
<td nowrap="nowrap"><?php echo '';?></td>
</tr>
<?php
$id++;
}
?>
</table>
I think you forgot some login...
Little Change in your code :--
if ($pplayer == $player) {
$sta = $record['score'];
}
else
{
unset($sta);
}
Add this condition to your code...

sort data columnwise by click on column header and sort in reverse by click again using codeigniter

hey guys i am new in codeigniter and i am working on a project in which i have a table fecthed from database..i want to sort table by click on table header how can i do that . . i am using a code like this:-
controller:
function index()
{
$config['total_rows'] = $this->db->get('tbl_members')-> num_rows();
$config['per_page'] = 2;
$segment_array=$this->uri->segment_array();
$segment_count=$this->uri->total_segments();
$do_orderby = array_search("orderby",$segment_array);
$asc = array_search("asc",$segment_array);
$desc = array_search("desc",$segment_array);
$this->db->order_by($this->uri->segment($do_orderby+1), $this->uri->segment($do_orderby+2));
if (ctype_digit($segment_array[$segment_count]))
{
$data['page']=NULL;
$this->db->limit($config['per_page']);
}
else
{
$data['page']=$segment_array[$segment_count];
$this->db->limit($config['per_page'], $segment_array[$segment_count]);
array_pop($segment_array);
}
$config['base_url'] = site_url(join("/",$segment_array));
$config["uri_segment"] = count($segment_array)+1;
$this->load->model('mod_user'); //load the mod_user class
$data['rows'] = $this->mod_user->getmembers();
//initialize pagination
$this->pagination->initialize($config);
$this->load->view('view_home',$data);
$this->load->view('view_homemember',$data);
}
my view is:
<form class="userinfo" action="" method="post">
<?php //if(count($rows) > 0) { ?>
<table border="1" cellpadding="2" cellspacing="0">
<?php
// For Sorting
//default in descending order
$sort['col1']='desc';
$sort['col2']='desc';
$sort['col3']='desc';
//get the segment array
$segment_array=$this->uri->segment_array();
//search for the orderby string
$do_orderby = array_search("orderby",$segment_array);
//check to toggle asc and desc sorting in columns
if($do_orderby !== FALSE) {
$sort[$segment_array[$do_orderby+1]]= $segment_array[$do_orderby + 2] == 'desc' ? 'asc' : 'desc' ;
}
?>
<tr>
<td width="5%;"> </td>
<td width="5%;"> </td>
<td width="15%;"><?php echo "";?>Name</td>
<td width="15%;">Moderator Name</td>
<td width="20%;">KCC Branch</td>
<td width="15%;">Father/Husband Name</td>
<td width="15%;">Address</td>
<td width="10%;">Date</td>
</tr>
There is an excellent tutorial on this, in the CodeIgniter from scratch" series:
http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-displaying-sorting-tabular-data/

php Multiple looping problem

Im writing a function to get the parent and child ids but for the third loop there is a
problem the loop gets even the previous loops id also .
How can i avoid it?
<?
$results = '
<table>
<thead>
<tr >
<td id="ticket" align="center" ><b>Task<br />ID</b></td>
<td id="ticket" align="center" ><b>col1</td>
<td id="ticket" align="center" ><b>col2</td>
</tr>
</thead>
<tbody>';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$results .='
<tr >
<td align="center">
'.$row['Task_id'].'
</td>';
$results .= '<td align="center">';
$gg = mysqli_query($dbc,"select * from Tasks where ParentTask_Id='".$row['Task_id']."'");
echo "<br>";
while ($rowdd = mysqli_fetch_assoc($gg))
{
$results .= $rowdd['Task_id']."<br><br>";
$gg2 = mysqli_query($dbc,"select * from Tasks where ParentTask_Id='".$rowdd['Task_id']."'");
while ($rowdd2 = mysqli_fetch_assoc($gg2))
{
$results2 = $rowdd2['Task_id']."<br><br>";
}
echo "<br>";
}
// $results .= $car ;
// $results .= $t;
$results .='</td>';
$results .=' <td align="left" >'?>
<?
$results .= $results2;
$results .='</td>';
$results .='
</tr>';
}
?>
Is the $results variable empty? I only see it being concatenated.
Also, on your table you have multiple ids that are the same. You either need to change that to a class or have a unique value for each id.

Categories