display student details if absent continuously for 5 days - php

I have a problem displaying students details who are absent for 5 days continuously. I wrote a sql query like :
$res = $this->db->findAll("SELECT
student_id,attn_date,count(is_absent) as absent FROM
sg_students_attendance where is_absent=1 GROUP BY student_id ORDER BY
attn_date desc");
The condition which I applied is:
foreach($res as $rec)
{
$abs=$rec['absent'];
$abs1=5;
if($abs1==$abs)
{
echo "<tr>";
echo "<td>".$rec['student_id'];
echo "<td>".$rec['absent'];
echo "</tr>";
}
}
I am getting students details those who are absent for 5 days but not continuously. What will be the query for that ???

You can do this with PHP code
$res=$this->db->findAll("SELECT student_id,attn_date,is_absent as absent FROM sg_students_attendance where is_absent=1 ORDER BY student_id,attn_date desc");
PHP code
$count = 0;
foreach($res as $rec)
{
$abs=$rec['absent'];
if($abs == 1)
$count++;
else
$count = 0;
if($count == 5)
{
echo $rec['student_id'] . ' is absent for continuous 5 or more days<BR>';
$count = 0;
}
}

Related

Values repeating itself for different sections in a report

I am building a exam report module which consists of three sections i.e. section 1 for 1 marks and 10 questions, section 2 for 2 marks and 5 questions and section 3 for 4 marks and 5 questions. Total number of questions are 20 and the total marks are 40. Now when a user finishes exam I am trying to display his result in a report showing section wise report. The issue emerging here is if a user attempts one section only and suppose he has secured 3 correct answers so the report must show 3 in section1 and 0 in other two sections but the report each time is fetching 3 for all the section or we can say all the sections has value of one section. What i need to show is number of "correct answers" 3-0-0 as the user has attempted only one section. Although currently it takes 3 for all the sections.
Here is my code for the frontend,
<tr><td>3</td>
<td>Correct Answers</td>
<td><?php echo $rep->sectionwiseMockReport($id, $chapterId,1); ?></td>
<td><?php echo $rep->sectionwiseMockReport($id, $chapterId,2); ?></td>
<td><?php echo $rep->sectionwiseMockReport($id, $chapterId,3); ?></td>
<td><?php echo ($rep->sectionwiseMockReport($id, $chapterId,1)+$rep->sectionwiseMockReport($id, $chapterId,2)+$rep->sectionwiseMockReport($id, $chapterId,3)) ; ?></td>
</tr>
And the function that is being called is into a class,
function sectionwiseMockReport($userId, $chapterId,$section)
{
$counter1 = 0 ;
$counter2 = 0 ;
$counter3 = 0 ;
$total = 0 ;
$result = mysql_query("SELECT question_id, option_id from tbl_result_chapter WHERE user_id = $userId AND chapter_id = $chapterId");
while($row = mysql_fetch_array($result))
{
if($this->getRightOptionChapter($row['question_id']) == $row['option_id'])
{
$section = $this->idToField("tbl_question_chapter","section",$row['question_id']);
if($section == 1)
{
$counter1 = $counter1 + 1 ;
}
if($section == 2)
{
$counter2 = $counter2 + 1 ;
}
if($section == 3)
{
$counter3 = $counter3 + 1 ;
}
}
}
if($section == 1)
{
return $counter1;
}
if($section == 2)
{
return $counter2;
}
if($section == 3)
{
return $counter3;
}
}
And lastly the function,
function getRightOptionChapter($questionId)
{
$result = mysql_query("SELECT * from tbl_chapter_answer a INNER JOIN tbl_chapter_options o on a.options_id = o.id WHERE a.question_id = $questionId");
$row = mysql_fetch_array($result);
return $row['options_id'];
}
Any suggestion or help will be a lifesaver. Had been looking for this for couple of days but no success at all.
Finally got the issue. The variable $section was creating the conflict inside while loop and outside of while loop. Changed the variable name inside the while loop and working swiftly.

PHP: For loop that repeats the first item instead of looping through all items?

I have a MySQL query that requests a list of items.
I fetch for them and want to display every item with a for loop, but it shows me just the first item repeated, instead of every item.
Why?
<?php
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$query = " SELECT cursoID, nombreCurso, estadoCurso
FROM cursos
WHERE estadoCurso='abierto'";
$buscarCurso = mysqli_query($conectar,$query);
$curso=mysqli_fetch_assoc($buscarCurso);
$totalRows = mysqli_num_rows($buscarCurso); //There are 3 rows of results
echo $totalRows;
for ($i=0; $i < $totalRows; $i++) {
echo '<br>';
echo $curso['nombreCurso'];
echo '<br>';
}
?>
The intended result is:
Curso 1
Curso 2
Curso 3
And instead I get
Curso 1
Curso 1
Curso 1
Your loop should be fetching from the result set on every iteration. The standard way (as in many examples given in the PHP documentation) is that you do this in the while condition:
$totalRows = mysqli_num_rows($buscarCurso); //There are 3 rows of results
echo $totalRows;
while ($curso=mysqli_fetch_assoc($buscarCurso)) {
echo '<br>';
echo $curso['nombreCurso'];
echo '<br>';
}
You need a loop for the query result. In this case, you'll get just one result and loop through that result 3 times.
<?php
while($curso = mysqli_fetch_assoc($buscarCurso)) {
// Do some stuff
echo '<br />' . $curso['nombreCurso'] . '<br />';
}
?>
First use prepared statement for block SQL injection than check this code
<?php
$conn = mysqli_connect(HOST, USER, PASS, DATABASE);
$select_cursos = $conn->prepare(" SELECT
cursoID, nombreCurso, estadoCurso
FROM cursos
WHERE estadoCurso = ? ORDER BY nombreCurso ASC
");
$select_cursos->bind_param('s', $nombreCurso);
$nombreCurso = 'abierto'; // This you can get from a $_POST too
if (!$select_cursos->execute()) { // ERROR
echo('Error');
} else { // OK
$select_cursos_result = $select_cursos->get_result();
$select_cursos_count = select_cursos_result->num_rows;
echo('Found: '.$select_cursos_count);
if ($select_cursos_count > 0) {
while ($data = $select_cursos_result->fetch_assoc()) {
echo ($data['nombreCurso'].'<br>');
}
} else {
echo ('No data!!');
}
}
?>
Cheers!!!

how to get the mysql columns names including the right result values in one loop

I ask in connection to this article:
How to get the columns names along with resultset in php/mysql?
$selecttable = mysql_query("SELECT * FROM $tablename WHERE (preis_bis <= '$price_upper' AND preis_bis > '$price_lower') LIMIT 1");
for ($i = 0; $i < mysql_num_fields($selecttable); $i++) {
$field_info = mysql_fetch_field($selecttable, $i);
// not WORKING
while($rowvalue = mysql_fetch_row($selecttable)) {
echo "<tr><td>Price: ".$rowvalue[$i]."</td></tr>";
}
echo "<tr><td style='border:1px solid #c0c0c0;padding:10px;'><!-- {$field_info->name} -->";
// get Logo and provider name
$select_getlogo = mysql_query("SELECT * FROM rrv_anbieter WHERE aid = '$field_info->name' LIMIT 1");
while($row_logo = mysql_fetch_object($select_getlogo)){
echo $row_logo->name.'<br><img src="images/'.$row_logo->logo.'" style="max-width: 200px;">';
}
#while($rowvalues2 = mysql_fetch_row($selecttable)) {
# foreach($rowvalues2 as $_column) {
# echo "<td>{$_column}</td>";
# }
#}
echo "</td></tr>";
}
I do not get it to get the correct row value within the "for" loop. Writing col names is working, but showing additionally the right value in same loop not.
Can someone help?
You need to iterate once more in the inner loop to get all rows of the table's columns.
while($rowvalue = mysql_fetch_row($selecttable)) {
foreach($rowvalue as $r){
echo "<tr><td> ".$r."</td></tr>";
}
}
$rowvalue[$i] showed rows incorrectly because it's following index based on the outer loop which is $i.
So basically the loop will print all rows of each column for n-times where n=number of all columns, not just the price column.
.
And you can also print all elements per-$rowvalue at once with :
while($rowvalue = mysql_fetch_row($selecttable)) {
$allElements = implode(",",$rowvalue ); // comma ',' is the separator
echo "<tr><td>". $allElements."</td></tr>";
}
}

Sort PHP - 2 columns with common subheaders

My code does the two columns, like this:
neighborhood 1
restaurant 1
neighborhood 1
restaurant 2
neighborhood 1
restaurant 3
I WANT:
neighborhood 1
restaurant 1
restaurant 2
restaurant 3
$result = mysql_query("SELECT ID,RName,NHood FROM Restaurants ORDER BY NHood ASC, TRIM(LEADING 'The ' FROM RName) ASC",$connect);
$numRows = mysql_num_rows($result);
$middleIndex = (int)(($numRows+1) / 2);
$names = array();
while($row = mysql_fetch_assoc($result)) {
$names[] = $row['RName'];
$id[] = $row['ID'];
$hood[] = $row['NHood'];
}
// print the left column
echo "<table>";
echo "<tr>";
echo "<td width=60%>";
echo "<div id=\"left\">\n";
for($i = 0; $i < $middleIndex; $i++) {
echo $hood[$i];
echo "<p>$names[$i]</p>\n";
}
echo "</div>\n";
echo "</td>";
// print the right column
echo "<td>";
echo "<div id=\"right\">\n";
for($i = $middleIndex; $i < $numRows; $i++) {
echo $hood[$i];
echo "<p>$names[$i]</p>\n";
}
echo "</div>\n";
echo "</tr>";
echo "</table>";
Here's the logic you want (pseduocode):
SELECT
ID,
RName,
NHood
FROM
Restaurants
ORDER BY
NHood ASC, RName ASC
This should return a list of results ordered first by the neighborhood, then by restaurant name.
Next, you'll process those results line-by-line to create a nested array with the data structure you want for your view:
$neighborhoods = array();
foreach($result as $row)
{
// Add each restaurant to a list named for the current neighborhood
$neighborhoods[$row['NHood']][] = $row['RName'];
}
This will produce a data structure like this:
$neighborhoods = array(
'neighborhood1' => array(
'restaurant1',
'restaurant2',
'restaurant3',
),
'neighborhood2' => array(
'restaurant1',
'restaurant2',
),
)
Which you will then use by doing this:
foreach($neighborhoods as $neighborhood => $restaurants)
{
echo $neighborhood;
foreach($restaurants as $restaurant)
{
echo $restaurant;
}
}
If your list is really large and you're worried about memory the implementation is a bit different but the logic is the same. This technique is faster but it's a bit harder to read and maintain because presentation and data layer logic are all mixed together:
$currentNH = null;
while($row = fetch_row($results))
{
// Detect when the neighborhood changes
if($currentNH != $row['NHood']) {
echo $row['NHood'];
}
echo $row['RName'];
}

php mysql - echo clear division after 3rd result

I echo results in DESC order from MySQL table with while loop. I've pagination system implemented already and its size is 9 records per page. The problem is, that if I do:
// ECHO CSS BREAK
if($row['id'] % 3 == 0){
echo '<li class="clear"></li>';
}
// SHOW VIDEOS
while($row = mysql_fetch_array($result)){
echo '<li>...echo code...</li>';
// problem = implement that echo css break in ASC order
}
Use a loop variable, e.g.
$i = 0;
Then instead of
if ($row['id'] % 3 == 0) {
do
if (++$i % 3 === 0) {
This makes sure it always happens are the third [sixth, ninth, ...] time.
You may want to get arbitrary rows from the database at another point in time, or shuffle the results -- relying on row IDs is not a good idea.
Is this what you are looking to implement?
// SHOW VIDEOS
while($row = mysql_fetch_array($result)){
if($row['id'] % 3 == 0){
echo '<li>...echo code...</li>';
echo '<li class="clear"></li>';
} else {
echo '<li>...echo code...</li>';
}
}

Categories