Jump to content

creating radio buttons from a loop type statement


karatekid36

Recommended Posts

In my db system, there are users, and this number will flucuate over time due to gaining and losing members.  For a page I would like to construct, I would like to have an attendance tracking system.  Right now I have the sql/db set up working perdfectly and now it is time to make the PHP/html interface.  What I want to do is have. a table with the left column being the members name and then the right column with three radio buttons; one for each attendance type(Present, Late Excused).  Right now I have code that will display the person's name and attendance percentage over a certain time period, but I don't know how I shoudl approach the inputting of the attendance via a PHP/html page.  Each radio button group name will obviously need a variable in it to seperate them from each other, this i know, but how do you write the script so that it has form handling for an infinite amount of items.  Please let me know if you need more clarification or coding ideas that may help push this along.  Also, feel free to rip apart my code so far.

<?php

// Page header.
echo '<h1 id="mainhead">Attendance</h1>';

// Make the query.
$query = "SELECT user_id, CONCAT_WS(', ', last_name, first_name) AS name FROM brothers WHERE status =\"Undergraduate\" ORDER BY last_name, first_name ASC";
$result = mysql_query ($query); // Run the query.

if  (!$result) {
    echo "The Query:
$query
Produced the error:
".mysql_error();
    exit;
}

// Table header.
echo '<table align="center" cellspacing="0" cellpadding="3">
<tr>
<td align="left"><b>Brother</a></b></td>
<td align="left"><b>Attendance</a></b></td>

</tr>
';

// Fetch and print all the records.
$bg = '#eeeeee'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee'); // Switch the background color.
echo '<tr bgcolor="' . $bg . '">
	<td align="left">' . $row['name'] . '</td>
	<td align="left">Present <input type ="radio" name="attend' . $row['user_id'] . '" value="' . $row['user_id'] . '" />
	                      Excused <input type ="radio" name="attend' . $row['user_id'] . '" value="' . $row['user_id'] . '" />
		         Unexcused <input type ="radio" name="attend' . $row['user_id'] . '" value="' . $row['user_id'] . '" /></td>
</tr>
';
}
echo '</table>';

mysql_free_result ($result); // Free up the resources.	

mysql_close(); // Close the database connection.


include ('includes/footer.html'); // Include the HTML footer.
?>

Link to comment
Share on other sites

You can make the data created from forms be arrays. I would suggest you use the user_id as the key. So, try these modifications:

 

<?php
while ($row = mysql_fetch_assoc($result)) {//mysql_fetch_assoc is identical to mysql_fetch_array(resultresource, MYSQL_ASSOC but with less typing 
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee'); // Switch the background color.
echo '<tr bgcolor="' . $bg . '">
	<td align="left">' . $row['name'] . '</td>
	<td align="left">Present <input type ="radio" name="attend['.$row['user_id'].']" value="Present" />
	                      Excused <input type ="radio" name="attend['.$row['user_id'].']" value="Excused" />
		         Unexcused <input type ="radio" name="attend['.$row['user_id'].']" value="Unexcused" /></td>
</tr>
';
}
?>

 

You will then have an array within the $_POST array called $attend.

 

It will contain keys which are the user_id and the value with either be present, excused, or unexcused dependant on the radio button selected. You can then loop through $attend array, and do whatever you wish with the values. You will be able to work out which user it relates to by using the keys of the array, and searching your database by user_id.

Link to comment
Share on other sites

From this new table create with the names and the attendance "record", i want to insert three things into  a table.  I want to insert the the meeting id(this will be passed from a previous page and I will figure that out later), the user_id, and the attendance record.  To get the users' names, the following query was made..

$query = "SELECT user_id, CONCAT_WS(', ', last_name, first_name) AS name FROM brothers WHERE status =\"Undergraduate\" ORDER BY last_name, first_name ASC";

The table we are going to insert these into is the attendance table.  I really dont know where to start to validate this kind of code because I am still at the beginning of my php/sql adventure.  The WHOLE file is included below.

<?php

session_name ('YourVisitID');
session_start(); // Start the session.

// If no session value is present, redirect the user.
if (!isset($_SESSION['user_id'])) {

// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
	$url = substr ($url, 0, -1); // Chop off the slash.
}
$url .= '/index.php'; // Add the page.
header("Location: $url");
exit(); // Quit the script.
}

$page_title = 'Brothers Of Psi Beta';


require_once ('includes/mysql_connect.php'); // Connect to the db.

$query = mysql_query("SELECT * FROM brothers WHERE user_id='$user_id'");
$row = mysql_fetch_assoc($query);

if ($row['admin'] == 'admin'){
include ('./includes/header_admin.html');

} else {

include ('./includes/header.html'); 

}

function format_cellphone ($cellphone)
{
     $cell = str_replace(' ', '', $cellphone);  // remove any spaces
     return  substr($cell,0,3) . '-' . substr($cell,3,3) . '-' . substr($cell,6) ;
}

// Page header.
echo '<h1 id="mainhead">Attendance</h1>';

// Make the query.
$query = "SELECT user_id, CONCAT_WS(', ', last_name, first_name) AS name FROM brothers WHERE status =\"Undergraduate\" ORDER BY last_name, first_name ASC";
$result = mysql_query ($query); // Run the query.

if  (!$result) {
    echo "The Query:
$query
Produced the error:
".mysql_error();
    exit;
}

// Table header.
echo '<table align="center" cellspacing="0" cellpadding="3">
<tr>
<td align="left"><b>Brother</a></b></td>
<td align="left"><b>Attendance</a></b></td>

</tr>
';

// Fetch and print all the records.
$bg = '#eeeeee'; // Set the background color.

while ($row = mysql_fetch_assoc($result)) {//mysql_fetch_assoc is identical to mysql_fetch_array(resultresource, MYSQL_ASSOC but with less typing 
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee'); // Switch the background color.
echo '<tr bgcolor="' . $bg . '">
	<td align="left">' . $row['name'] . '</td>
	<td align="left">Present <input type ="radio" name="attend['.$row['user_id'].']" value="Present" />
	                      Excused <input type ="radio" name="attend['.$row['user_id'].']" value="Excused" />
		         Unexcused <input type ="radio" name="attend['.$row['user_id'].']" value="Unexcused" /></td>
</tr>
';
}




echo '</table>';

mysql_free_result ($result); // Free up the resources.	

mysql_close(); // Close the database connection.


include ('includes/footer.html'); // Include the HTML footer.
?>

Link to comment
Share on other sites

Ok, the process will be something like:

 

<?php
$attend  = $_POST['attend'];
$meeting_id = '';//not sure how you're going to get this so ive left it blank;
foreach($attend as $key => $value){
	mysql_query("INSERT INTO `attendance_table` (`meeting_id`,`user_id`,`attendance`) VALUES('$meetind_id','$key','$value')")or die(mysql_error());
	}
?>

 

You will, of course, also need to validate the data from the form to make sure the data it what you expect and not the working of a malicious user.

Link to comment
Share on other sites

I appreciate the help so far, but my next questions is directed towards how one would validate this information put in by the user not knowing how many people are going to loaded into this form because the amount of members will change once new members come in and old ones leave.  Can you only validate a form if you know all of the included parts or can you validate the form for an infinite number of items as long as the format is all the same?

Link to comment
Share on other sites

This code seems to submit when you click on the submit button, but when I check in the DB there is no information there.  It should be inserting the eid(event id), mid(member id), and the attend_status(attendance record) for each member that is pulled from the brothers table.  I am trying to debugg this but I am having no luck.  Any help would be greatly appreciated. 

 

<?php

session_name ('YourVisitID');
session_start(); // Start the session.

// If no session value is present, redirect the user.
if (!isset($_SESSION['user_id'])) {

// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
	$url = substr ($url, 0, -1); // Chop off the slash.
}
$url .= '/index.php'; // Add the page.
header("Location: $url");
exit(); // Quit the script.
}
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {

$errors = array(); // Initialize error array.

	// Check for a first name.
if (empty($_POST['first_name'])) {
	$errors[] = 'You forgot to enter your first name.';
} else {
	$fn = escape_data($_POST['first_name']);
}

if (empty($errors)) { // If everything's OK.

// Make the query.

$attend  = $_POST['attend'];
$meeting_id = '1';//not sure how you're going to get this so ive left it blank;
foreach($attend as $key => $value){
	mysql_query("INSERT INTO attendance ('eid', 'mid','attend_status') VALUES('$meetind_id','$key','$value')")or die(mysql_error());
	}
// Redirect the user to the view_users.php page.
			// Start defining the URL.
			$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);

			// Check for a trailing slash.
			if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
				$url = substr ($url, 0, -1); // Chop off the slash.
			}

			// Add the page.
			$url .= '/attendance.php';

			header("Location: $url");
			exit();

	} else { // If it did not run OK.
			$errors[] = 'You could not be registered due to a system error. We apologize for any inconvenience.'; // Public message.
			$errors[] = mysql_error() . '<br /><br />Query: ' . $query; // Debugging message.


} // End of if (empty($errors)) IF.

} else { // Form has not been submitted.

$errors = NULL;

} // End of the main Submit conditional.

// Begin the page now.

$page_title = 'Brothers Of Psi Beta';


require_once ('includes/mysql_connect.php'); // Connect to the db.

$query = mysql_query("SELECT * FROM brothers WHERE user_id='$user_id'");
$row = mysql_fetch_assoc($query);

if ($row['admin'] == 'admin'){
include ('./includes/header_admin.html');

} else {

include ('./includes/header.html'); 

}



// Page header.
echo '<h1 id="mainhead">Attendance</h1>';

// Make the query.
$query = "SELECT user_id, CONCAT_WS(', ', last_name, first_name) AS name FROM brothers WHERE status =\"Undergraduate\" ORDER BY last_name, first_name ASC";
$result = mysql_query ($query); // Run the query.

if  (!$result) {
    echo "The Query:
$query
Produced the error:
".mysql_error();
    exit;
}

// Table header.
echo '<form action="take_attend.php" method="post"><table align="center" cellspacing="0" cellpadding="3">
<tr>
<td align="left"><b>Brother</a></b></td>
<td align="left"><b>Attendance</a></b></td>

</tr>
';

// Fetch and print all the records.
$bg = '#eeeeee'; // Set the background color.

while ($row = mysql_fetch_assoc($result)) {//mysql_fetch_assoc is identical to mysql_fetch_array(resultresource, MYSQL_ASSOC but with less typing 
$bg = ($bg=='#eeeeee' ? '#ffffff' : '#eeeeee'); // Switch the background color.
echo '<tr bgcolor="' . $bg . '">
	<td align="left">' . $row['name'] . '</td>
	<td align="left">Present <input type ="radio" name="attend['.$row['user_id'].']" value="Present" />
	                      Excused <input type ="radio" name="attend['.$row['user_id'].']" value="Excused" />
		         Unexcused <input type ="radio" name="attend['.$row['user_id'].']" value="Unexcused" /></td>
</tr>
';
}




echo '</table>	<p><input type="submit" name="submit" value="Take attendance" /></p>
<input type="hidden" name="submitted" value="TRUE" />';

mysql_free_result ($result); // Free up the resources.	

mysql_close(); // Close the database connection.


include ('includes/footer.html'); // Include the HTML footer.
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.