Table of checkboxes and radio buttons

Maybe this sample is closer to what you need.

<?php

if(isset($_POST['submit'])):
    //echo "<pre>";
    //print_r($_POST);
    //echo "</pre>";
    
    if(isset($_POST['absence']) || isset($_POST['late'])):
        include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';
        try
        {
        foreach($_POST['student'] as $key => $studentID):
        
            if(array_key_exists($key,$_POST['absence']) || array_key_exists($key,$_POST['late'])):
            
                $studentid = $_POST['student'][$key];
                $courseid  = $_POST['course'][$key];
                $absence   = (array_key_exists($key,$_POST['absence']) ? $_POST['absence'][$key] : '0');
                $late      = (array_key_exists($key,$_POST['late']) ? $_POST['late'][$key] : '0');
                
                $sql = 'INSERT INTO notes SET
                  userid = :studentid
                , courseid = :courseid
                , date = CURDATE()
                , late = :late
                , absence = :absence';
                $s = $pdo->prepare($sql);
                
                $s->bindParam(':studentid', $studentid);
                $s->bindParam(':courseid', $courseid);
                $s->bindParam(':absence', $absence);
                $s->bindParam(':late', $late);
                $s->execute();
                 
                 
            endif;
            
        endforeach;    
        
        }
        catch (PDOException $e)
        {
            $error = 'Error adding submitted daily notes data. Click the back button to continue.';
            include 'error.html.php';
            exit();
        }
        header('Location: .');
        exit();
        
    endif;
endif;  
?>
<form action="" method="post">
           <table>
            <tr>
            <th>Course</th>
            <th>Student</th>
            <th>Absence</th>
            <th>Late</th>
            </tr>
            <?php $x = 1;?>
            <?php foreach (array_reverse($courses) as $course): 
            foreach (array_reverse($learners) as $learner): ?>
                          <?php if($course['id']==$learner['courseid']): ?>
                     <tr>
                      <td> 
                            <?php htmlout($course['course']) ?>
                      </td>
                        <td>           
                            <?php htmlout($learner['learner']);?> 
                        </td>
                        <td>
                            <input type="hidden" name='course[<?php echo $x; ?>]' value="<?php htmlout($course['id'])?>">
                            <input type="hidden" name='student[<?php echo $x; ?>]' value="<?php htmlout($learner['courseid']);?>">
                           <input type="checkbox" name="absence[<?php echo $x; ?>]" value="1"> 
                        </td> 
                        <td>
                           <input type="checkbox" name="late[<?php echo $x; ?>]" value="1"> 
                        </td>
                        </tr>
                        <?php endif; ?>
                <?php endforeach; ?>   
                <?php $x++;?>   
        <?php endforeach; ?>
        </table>
        <input type="submit" name="submit" value="Submit"> 
        </form>

Hi,

Yes the latest table you posted is what I am looking for.

The sql file is here,

http://www.shanegibney.com/shanegibney/filemgmt/index.php?id=23

This file contains the three tables for ‘learners’, ‘courses’ and ‘notes’.

The table called ‘learners’ looks like this,

The ‘courses’ table looks like this,

and the ‘notes’ table looks like this,

The $courses array is built with this file,

<?php
  include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';

  try
  {
    $result = $pdo->query('SELECT id, course FROM courses');
  }
  catch (PDOException $e)
  {
    $error = 'Error fetching list of courses.';
    include 'error.html.php';
    exit();
  }
  foreach ($result as $row)
  {
    $courses[] = array('id' => $row['id'], 'course' => $row['course']);
  }

The $learners array is built similarly,

<?php
  include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';
  
  try
  {
    $result = $pdo->query('SELECT id, learner, courseid FROM learners');
  }
  catch (PDOException $e)
  {
    $error = 'Error fetching list of learners.';
    include 'error.html.php';
    exit();
  }
  foreach ($result as $row)
  {
    $learners[] = array('id' => $row['id'], 'learner' => $row['learner'], 'courseid' => $row['courseid']);
  }

print_r($courses)

Array
(
    [0] => Array
        (
            [id] => 23
            [course] => Course4
        )

    [1] => Array
        (
            [id] => 21
            [course] => Course3
        )

    [2] => Array
        (
            [id] => 24
            [course] => Course2
        )

    [3] => Array
        (
            [id] => 25
            [course] => Course1
        )

    [4] => Array
        (
            [id] => 26
            [course] => Computing
        )

)

and print_r($learners)

Array
(
    [0] => Array
        (
            [id] => 24
            [learner] => Student10
            [courseid] => 21
        )

    [1] => Array
        (
            [id] => 25
            [learner] => Student9
            [courseid] => 22
        )

    [2] => Array
        (
            [id] => 26
            [learner] => Student8
            [courseid] => 23
        )

    [3] => Array
        (
            [id] => 27
            [learner] => Student7
            [courseid] => 24
        )

    [4] => Array
        (
            [id] => 28
            [learner] => Student6
            [courseid] => 25
        )

    [5] => Array
        (
            [id] => 29
            [learner] => Student5
            [courseid] => 21
        )

    [6] => Array
        (
            [id] => 30
            [learner] => Bessie Bunter
            [courseid] => 25
        )

    [7] => Array
        (
            [id] => 31
            [learner] => Student3
            [courseid] => 24
        )

    [8] => Array
        (
            [id] => 32
            [learner] => Student2
            [courseid] => 23
        )

    [9] => Array
        (
            [id] => 34
            [learner] => Tiny Tim
            [courseid] => 26
        )

)

I thought I could just read through each array element by element. But now I am thinking that the nth element in absence may not be from the same row as the nth element from late, because if on a particular row of the html table, has late checked but not absence, then they will be out of sync.
thanks,
Shane

Hi,

Drummin I see you use,

name=‘course[<?php echo $x; ?>]’

to identify the name for each row.

So you will get course1 and absence1 and late1 etc. all for the first row.

I was trying to use,

name=‘course

and then just go through each one element at a time. But your way is better.

The only reason I was using absence was because Kevin Yank suggests it in his book which I have been working through, PHP From Novice to Ninja’. This is discussed on page 222. A pdf can be found here.

http://www.google.ch/url?sa=t&rct=j&q=&esrc=s&source=web&cd=8&cad=rja&uact=8&ved=0CE8QFjAH&url=http%3A%2F%2Fwww.interstatearchive.com%2Flibrary%2FPHP_MySQL5.pdf&ei=pBpyVMP1NYTZywPCzILYCQ&usg=AFQjCNF9o7nManUJYlDvXL_-b7P1jjG5kQ&sig2=RuKypBv3M9VTvE733V6qZw&bvm=bv.80185997,d.bGQ

Although I have bought it!!!

Thanks,
Shane

So did you get it to work?

I believe the line quoted above needs to be changed so that the student id is the value.

<input type="hidden" name='student[<?php echo $x; ?>]' value="<?php htmlout($learner['id']);?>">

Hi,
I have put it all together but instead of the form there is a blank page.

I need to ask some stupid and basic questions.

In this line below,

<input type="hidden" name='course[<?php echo $x; ?>]' value="<?php htmlout($course['id'])?>">

Is it correct that this sets up the array called $_POST with elements with keys called course1, course2, course3 etc and each has a a value, in this case those values are each of the course’s ids?

Also, is there any reason for a change from single to double quotes in the name=‘…’ and name=“…” for the student hidden type and absence checkboxes?

But this is the bit i really need to understand,

foreach($_POST['student'] as $key => $studentID):
    if(array_key_exists($key,$_POST['absence']) || array_key_exists($key,$_POST['late'])):

This examines the key in each element of the array ‘student’ which is sent via the $_POST array. Each key is set equal to the variable $key and the value of which is set equal to the variable $studentID. This is repeated for each row or element of the ‘student’ array.
The if condition then uses OR to check if true for each of the functions. These functions check if there is the variable $key, which might be student1, and see if that key is in the absence array. Is that correct?..No, this is not correct

And checks if this might be true for the $late array, one or the other or both.

So does that mean that each key in ‘student’ must have a key the same in ‘absence’?.. No that can’t be right! Because the key called student1 only exists in student. Its equivalent in absence is absnece1 and course1 in ‘course’.

The foreach() goes through each element or row of student. But within the foreach loop when it encounters another array such as ‘course’, then the $key is actually the nth element of that array. Wow, is that correct? So it is stepping through each array in parallel. So when it is reading the 7th key and value from ‘student’ it is also reading the 7th element and it’s key and value from the array ‘course’.

I am not sure if that is correct but it seems to be what is happening here.

Also i haven’t seen this before,

$late      = (array_key_exists($key,$_POST['late']) ? $_POST['late'][$key] : '0');

But I presume is checks to see if the key called $key exists in the array ‘late’ and if it does sets the variable $late equal to its value. If that key doesn’t exist, it sets $late equal to zero. So there will always be a value going into the table for every field in every row.

I think I understand it now… so why isn’t it working? :smile:

Thanks,

Shane

Make sure you update that line of code I posted above regarding student id.

If you uncomment that print_r($_POST), (seen on my copy) you should get a better understanding of what $key represents. Just like in the html table the key is unique for each row. 1, 2, 3 etc the key for each POST will represent the same set of primary POST keys, student, course and absence or late if selected. SO the $key in the foreach loop will also be those 1, 2, 3 numbers but $_POST[‘absence’] will only have a number if the radio button was selected. So say $_POST[‘absence’][6] is the only one selected. As the foreach loops and gets to 6 that array_key_exists will be true so coding within this condition is run. As we want to run an update query if either absence or late is present we check for either using ||.

At this point, I’m more concerned about the blank page. Something must be missing.

Crank-up PHP’s error reporting to report everything:

error_reporting(E_ALL);
ini_set('display_errors', 1);

Does a parser error then get reported? (btw for a live site you’ll want to not display errors - instead logging them to an error log)

Hi,
Here is what I have for index.php and it is basically the same as you posted in post 17 of this thread.

if (isset($_GET['addnotes']))
{
    echo "<pre>";
    print_r($_POST);
    echo "</pre>";
   include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/db.inc.php';
    if(isset($_POST['absence']) || isset($_POST['late'])):
        try
        {
        echo "hello world";
        foreach($_POST['student'] as $key => $studentID):
            if(array_key_exists($key,$_POST['absence']) || array_key_exists($key,$_POST['late'])):
                $studentid = $_POST['student'][$key];
                $courseid  = $_POST['course'][$key];
                $absence   = (array_key_exists($key,$_POST['absence']) ? $_POST['absence'][$key] : '0');
                $late      = (array_key_exists($key,$_POST['late']) ? $_POST['late'][$key] : '0');
                $sql = 'INSERT INTO notes SET
                  userid = :studentid,
                  courseid = :courseid,
                  date = CURDATE(),
                  late = :late,
                  absence = :absence';
                $s = $pdo->prepare($sql);
                $s->bindParam(':studentid', $studentid);
                $s->bindParam(':courseid', $courseid);
                $s->bindParam(':absence', $absence);
                $s->bindParam(':late', $late);
                $s->execute();
            endif;
        endforeach;    
        }
        catch (PDOException $e)
        {
            $error = 'Error adding submitted daily notes data. Click the back button to continue.';
            include 'error.html.php';
            exit();
        }
        header('Location: .');
        exit();
    endif;
endif; 

and the notes.html file

<?php include_once $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/helpers.inc.php';  
      include_once $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/func.inc.php'; 
      include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/buildcourses.inc.php';
      include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/buildlearners.inc.php';?>
<!DOCTYPE html>
<html lang="en">
  <head>
  <style>
table,th,td
{
border-collapse:collapse;
}
th, td
{
padding:6px;
}
        td { text-align: center; width: 40px; overflow: hidden;  white-space: nowrap;}
</style>
    <meta charset="utf-8">
    <title>Manage Daily Notes</title>
  </head>
  <body>
      <p><a href="..">physCMS home</a></p>
      <p><a href="?arraytestTWO">array Test</a></p>
      <?php include $_SERVER['DOCUMENT_ROOT'] . '/artgibney/includes/logout.inc.html.php'; ?>
    <h1>Manage Daily Notes</h1>
    <p><a href="?addcourseform">Add Course</a>  &#8658;  
    <? if(countRows('courses')): ?>
     <a href="?addlearnerform">Add Student</a>
    <? endif; ?>  
    <? if(countRows('learners')): ?>
       &#8658;  
       <a href="?courses">Manage Courses and Students</a></p>
    <? endif; ?>
                 <form action="?addnotes" method="post">
           <table>
            <tr>
            <th>Course</th>
            <th>Student</th>
            <th>Absence</th>
            <th>Late</th>
            </tr>
            <?php $x = 1;?>
            <?php foreach (array_reverse($courses) as $course): 
            foreach (array_reverse($learners) as $learner): ?>
                          <?php if($course['id']==$learner['courseid']): ?>
                     <tr>
                      <td> 
                            <?php htmlout($course['course']) ?>
                      </td>
                        <td>           
                            <?php htmlout($learner['learner']);?> 
                        </td>
                        <td>
                            <input type="hidden" name="course[<?php echo $x; ?>]" value="<?php htmlout($course['id'])?>">
                            <input type="hidden" name="student[<?php echo $x; ?>]" value="<?php htmlout($learner['id']);?>">
                           <input type="checkbox" name="absence[<?php echo $x; ?>]" value="1"> 
                        </td> 
                        <td>
                           <input type="checkbox" name="late[<?php echo $x; ?>]" value="1"> 
                        </td>
                        </tr>
                        <?php endif; ?>
                <?php endforeach; ?>   
                <?php $x++;?>   
        <?php endforeach; ?>
        </table>
        <input type="submit" name="submit" value="Submit"> 
        </form>
  </body>
</html>

As I said the form is not displaying. There is some tiny typo I know. But I can’t find it.
I tried

echo “hello”;

in the index.php and can’t see that. Until I can there I won’t get be able to use print-r()

I have just had a look at error_log

[23-Nov-2014 16:08:21 America/Denver] PHP Parse error:  syntax error, unexpected 'endif' (T_ENDIF) in /home2/shanegib/public_html/artgibney/admin/notes/index.php on line 76
[24-Nov-2014 11:50:21 America/Denver] PHP Parse error:  syntax error, unexpected 'endif' (T_ENDIF) in /home2/shanegib/public_html/artgibney/admin/notes/index.php on line 76
[24-Nov-2014 12:13:31 America/Denver] PHP Parse error:  syntax error, unexpected 'endif' (T_ENDIF) in /home2/shanegib/public_html/artgibney/admin/notes/index.php on line 80

Looks like there may be an extra endif
Not sure why it says Denver. Maybe that’s where the Bluehost server is.
Going to look for the extra endif now.
Thanks,
Shane

Thanks,
Shane

I see three if openings and three endif closing.
So I don’t know why the error_log tells me there is an extra endif in line 80 of index.php
Unless it is in the form.
Looking now!

Got it! The first if loop uses the if(…){…} syntax and the others use if(…):… endif; syntax
It is working now. Well the form is showing.
There is now an error submitting data to the database but i can see the array from print_r() so I have plenty to play with for the moment.
Thanks,
Shane

Ya, I was going to say change

if (isset($_GET['addnotes']))
{

to

if (isset($_GET['addnotes'])):

Too bad you keep insisting to use that GET value to trigger POST processing. Just add the name to the submit button like I’ve done on my examples.

But the index.php file has many of these,
if (isset($_GET[‘BLAH’]))
{
}
If I just use ‘submit’ how will I identify which to use?
Although I can change $_GET to $_POST if it is better.
Thanks,
Shane

Each can have their own name, e.g.

<input type="submit" name="addnotes" value="Submit" />

And their own value?
I am trying to post what I have. But I am using GNU now and trying to install Gimp too make a screenshot but it is getting messy with the packages not updating correctly. Might need to go back to Windows!!!

Can you sort out the query issue? Getting any errors?

The following submission,

produces the following,


Only two absences and one late are being sent to the POST array. The problem seems to be when an absence and late are on the same row only the absence gets sent. It seems that only the last student from each course is being considered.
Also why are there only 5 elements in the students array? There are 8 students.
I did change the $x initial value to 0 in the html file.
Thanks,
Shane

Hi,
Fixed that. The $x++ needs to be inside both foreach() loops in the html form.
This looks correct now,

And this gives,


I know it doesn’t make sense that a student can be absent and late but it is fine.
Why are the keys numbered 0, 11, 13, 18, 22, 28, 33, 39 and not just 0,1, 2, 3, 4, 5, 6, 7 ?
Although they do match correctly with the absences and lates.
Thanks,
Shane

The change in $x++ now increments on each cell instead of row.

The NAME of the radio button could be changed to attend with a value of absence, late etc. By having the same name they would then toggle. Would just need to adjust processing for new values.

Ok, I moved the $x++ inside the endif; so it now only increments after each row.

       <table>
        <tr>
        <th>Course</th>
        <th>Courseid</th>
        <th>Student</th>
        <th>Studentid</th>
        <th>Absence</th>
        <th>Late</th>
        </tr>
        <?php $x = 0;?>
        <?php foreach (array_reverse($courses) as $course): 
        foreach (array_reverse($learners) as $learner): ?>
                      <?php if($course['id']==$learner['courseid']): ?>
                 <tr>
                  <td> 
                        <?php htmlout($course['course']) ?>
                  </td>
                  <td> 
                        <?php htmlout($course['id']) ?>
                  </td>
                    <td>           
                        <?php htmlout($learner['learner']);?> 
                    </td>
                    <td> 
                        <?php htmlout($learner['id']) ?>
                  </td>
                    <td>
                        <input type="hidden" name="course[<?php echo $x; ?>]" value="<?php htmlout($course['id'])?>">
                        <input type="hidden" name="student[<?php echo $x; ?>]" value="<?php htmlout($learner['id']);?>">
                       <input type="checkbox" name="absence[<?php echo $x; ?>]" value="1"> 
                    </td> 
                    <td>
                       <input type="checkbox" name="late[<?php echo $x; ?>]" value="1"> 
                    </td>
                    </tr>
                     <?php $x++;?>  
                    <?php endif; ?>
            <?php endforeach; ?>   
    <?php endforeach; ?>
    </table>

Seems to be correctly sending data to Post now.

And the array,

Array
(
    [course] => Array
        (
            [0] => 26
            [1] => 25
            [2] => 25
            [3] => 24
            [4] => 24
            [5] => 21
            [6] => 23
            [7] => 23
        )

    [student] => Array
        (
            [0] => 34
            [1] => 30
            [2] => 28
            [3] => 31
            [4] => 27
            [5] => 29
            [6] => 32
            [7] => 26
        )

    [absence] => Array
        (
            [1] => 1
            [3] => 1
            [5] => 1
            [6] => 1
        )

    [late] => Array
        (
            [2] => 1
            [3] => 1
            [6] => 1
        )

    [submit] => Submit
)
      Error adding submitted daily notes data. Click the back button to continue. 

Thanks,
Shane