Jump to content

Send boolean value in populated checkbox


vindesigns

Recommended Posts

Hi all,

 

I wonder if you guys can help me, I'm pretty new to PHP. I’m creating a module information system which allows a student to view all the compulsory and optional modules that can be studied within a course. Once a module has been created it then can be associated with a course.

 

In the admin section I have created a page which allows you to create a module, I’m in the process of creating the course page where it allows the admin to create a course and select the modules the course comprises of. I would like the admin to have the ability to select if the module is compulsory or optional.

 

Here is an interface design for the courses page.

http://www.2shared.com/photo/mw168s7U/C ... rface.html

 

At the moment this is what my table structure is (ERD). http://www.2shared.com/photo/KyCPT4gl/ERD_Model.html

 

In the join table (coursemodule) I have four attributes (ID, courseID, moduleID, iscore). When a new course has been created and modules are selected it sends the ID of the course and module into the join table.

I would like to populate a second checkbox which would appear next to the module which when both check boxes are checked it would send a ‘1’ to the ‘iscore’ attribute and if it is unchecked but the first checkbox is selected it would send ‘0’ to the ‘iscore’ attribute.

 

I have set the ‘iscore’ field to Boolean but am struggling what piece of code I would need to write in order to send these values in a check box. I wonder if you guys could help. Thanks

 

Here is the code within the courses page:

//

<form action="course_add.php" method="post" enctype="multipart/form-data" name="upload">
<table width="644">
<tr>
<td width="151">Course Title</td>
<td width="481"><span id="sprytextfield1">
<label for="moduleCode"></label>
<input name="courseTitle" type="text" id="courseTitle" />
<span class="textfieldRequiredMsg">A value is required.</span></span></td>
</tr>
<tr>
<td>Course Modules</td>
<td>

<?php
//This block creates a list of modules from the modules table

$category_list = "";
// $iscore = "";

$sql2 = "SELECT * FROM modules";

$result2 = mysql_query($sql2) or die(mysql_error());

$catCount = mysql_num_rows($result2); //count the output amount
//echo 'No of categories: '.$catCount.'<br>';

if($catCount > 0){
while($row2 = mysql_fetch_array($result2)){

$isCore = false;
$moduleID = $row2["moduleID"];
$catName = $row2["moduleTitle"];
// $category_list .= '<input type="checkbox" name="module[]" id="module[]" value="'.$moduleID.'" /> '.$catName.' ';

$category_list .= '<input type="checkbox" name="module[]" id="module[]" value="'.$moduleID.'" /> <input type="checkbox" name="core" id="core" value="1" />  '.$catName.'<br>';
}

} else {
$product_list = "Unable to create category list";
}
echo $category_list;

?>

</td>
</tr>
<tr>
<td> </td>
<td>
<input type="hidden" name="dbtable" value="courses" />
</td>

</tr>
<tr>
<td> </td>
<td><div align="right">
<input type="submit" value="Add Course" />
</div></td>
</tr>
</table></form>

 

-------------------------------------------------------

 

// Here is the php code in the course_add.php file


<html>
<head>
<title>Uploading...</title>
</head>
<body>
<h1>Uploading...</h1>
<p>
<?php
require_once('../../Connections/module_system.php');
echo '<br><b>modules: </b>';
foreach($_POST['module'] as $cats)
{
echo $cats.', ';
}
echo '<br><h3>Uploading course details to the database...</h3>';

$courseTitle=$_POST['courseTitle'];



$query = "INSERT INTO courses (courseTitle) VALUES ('".$courseTitle."')";

$result = mysql_query($query);

$pid = mysql_insert_id();

//echo pull out course ID from last record inserted to enter into course module table

echo '<b>ID of last inserted Course is = '.$pid.'</b><br>';

//SQL for modulecourses
echo '<h3>Uploading course module information to the database...</h3>';
$cats_upload = "";
foreach($_POST['module'] as $cats)
{
$isCore=$_POST['core'];

echo $pid.' - '.$cats.' - '.$isCore.'<br>';
$query2 = "INSERT INTO coursemodule (courseID, moduleID, iscore) VALUES ('".$pid."','".$cats."','".$isCore."')";
$result2 = mysql_query($query2);
if ($result2) {
$cats_upload = $cats_upload + mysql_affected_rows(); //
} else {
echo "an error has occurred uploading to the coursemodule table.<br>";
}
}
echo 'Number of Modules Uploaded: '.$cats_upload;
?>

 

----

 

Please let me know if you have any ideas.

 

Thanks

 

MOD EDIT: code tags added.

Link to comment
Share on other sites

Man, too much text, links and code, I just skimmed through it. From what I understand, you want another checkbox, that will send 1 when checked or 0 when not checked.

input type="checkbox" name="NEWCHEKBOXNAME" value="1" />

then on form submission use isset

(unset checkboxes do not get sent with form, so if it does not exist, your value is 0, if it exists, value is 1)

if(isset($_POST['NEWCHECKBOXNAME'])){
   // do something, check other value, whatever...
   if($othervalue==1) $iscore = 1;
}else{
   $iscore = 0;
}

 

hope this helps

Link to comment
Share on other sites

Hi,

 

Thanks for the quick reply. Have been away so not been able to contact you.

 

I'm pretty new to php so bare with me please.

 

As you mentioned when the second checkbox is ticked too it will put' 1' into the iscore field and when it is unchecked but the first checkbox is ticked it will sent a '0'. I've tried to put this into practice but I'm probably doing something wrong. Here is your code that I tried to put in, it actually sends a 0 through when ticked and unticked now.

 


if($catCount > 0){
while($row2 = mysql_fetch_array($result2)){


	$moduleID = $row2["moduleID"];
	$catName = $row2["moduleTitle"];


$category_list .= '<input type="checkbox" name="module[]" id="module[]" value="'.$moduleID.'" /> <input type="checkbox" name="core[]" value="1" />  '.$catName.'<br>';

 

 

then on submission I put the code here:

 

//SQL for modulecourses
echo '<h3>Uploading Product Category information to the database...</h3>';
$cats_upload = "";

foreach($_POST['module'] as $cats)

{
if(isset($_POST['core[]'])){
   // do something, check other value, whatever...
   if($othervalue==1) $isCore = 1;
}else{
   $isCore = 0;
}


echo $pid.' - '.$cats.' - '.$isCore.'<br>';


$query2 = "INSERT INTO coursemodule (courseID, moduleID, iscore) VALUES ('".$pid."','".$cats."','".$isCore."')";

 

 

I don't know whether I'm putting it in the right place or not, please let me know where I'm going wrong. Thanks

 

Link to comment
Share on other sites

As you mentioned when the second checkbox is ticked too it will put' 1' into the iscore field and when it is unchecked but the first checkbox is ticked it will sent a '0'. I've tried to put this into practice but I'm probably doing something wrong. Here is your code that I tried to put in, it actually sends a 0 through when ticked and unticked now.

 

I actually didn't say that. I said if checked it would send 1, if not checked it wouldn't even be posted with the form.

 

From what I see in your code, you need to understand some other things first.

 

An array will hold several values. These values all have a key so that you can access them. as in $var = array("A","B","C");

$var[0] would be A (the key is 0), $var[1] would be B (the key is 1)... etc. These keys can also be names, so I could do this: $var = array("key1"=>"A","johnny"=>"B","SimpleSimon"=>"C");

$var['SimpleSimon'] would be C, $var['johnny'] would be B... etc.

 

Keeping this in mind, I could say that $var['johnny'] = array("A","B","C"); (instead of it's current value that is B.

Now johnny is an array inside or another array ($var).

 

$var['johnny'][1] would be B.

 

now look at your code again and think about this...

if( isset($_POST['core[]']) ){

what you want to find out with that is if the array called core exists in the $_POST variable. Even though core is an array, you access it by it's name only, so

if( isset($_POST['core']) ){

is the correct code. The fact that the array core exists, does not mean it has any data, so you can check that with:

if( isset($_POST['core']) && !empty($_POST['core']) ){

...

so far so good... but now you have another problem.

You told your html form, that there would be an element named core and it would be an array (core[]).

this means that when core gets posted, the values in it will be in indexed from 0 to .. whatever

$_POST['core'][0]

$_POST['core'][1]

$_POST['core'][2]

...

How will you know which is the one you need? Either you're only sending 1 in each POST, and in that case $_POST['core'][0] will always be the correct one, but that also eliminates the need for core to be an array, and all this conversation would be a waste... Or you can add the module code to it, so that you can use it as the key to check if the checkbox was clicked or not, like this:

 

$category_list .= '<input type="checkbox" name="module[]" id="module[]" value="'.$moduleID.'" /> <input type="checkbox" name="core['.$moduleID.']" value="1" />  '.$catName.'<br>';

 

Now you know, that when it gets posted, the final result can be accessed with:

$_POST['core'][<MODULEID>]...

since you're already looping through $_POST['module'] with your foreach loop,

what you need to do is something like this:

foreach($_POST['module'] as $cats){
if( isset($_POST['core'][$cats]) ){

 

Get it? you will be using each ModuleID as a key to access your core[] array. And if $_POST['core'][$cats] exists, it's value will always be 1. (as I told you before, unchecked checkboxes do not get sent in the form, so they do not exist)

 

Hope this helps (and that it makes sense)

 

Link to comment
Share on other sites

Hi there,

 

Thanks for your detailed explanation , it makes much more sense now and I understand it a lot more. From your help I have now been able to to send the value 1 to the coursemodule table if the checkbox has been checked. Thanks again :).

 

I have moved onto the editing side of where the admin would be able to edit the courses. When an admin tries to edit a course they will be able to edit all course info and see all the compulsory and optional modules that are associated with the course.

 

I have managed to populate the check box and if the course is associated with any modules by looking in the coursemodule table then it will be checked. I'm struggling to work out how to check the box if there is a value in the iscore attribute; so if there is the value 1 it would be checked and if 0 then it would be unchecked. I have only made the check box appear up to now do not know if the $isCore = 1 is put when the "if($count > 0){" is done.

 

Below is the code up to now.

 


<?php
//This block creates a list of modules from the modules table
$prodID = $_GET['pid'];
//echo "PID = ".$prodID."<br>";

$category_list = "";
$sql2 = "SELECT * FROM modules";
$result2 = mysql_query($sql2) or die(mysql_error());
$catCount = mysql_num_rows($result2); //count the output amount


if($catCount > 0){
while($row2 = mysql_fetch_array($result2)){
	$moduleID = $row2["moduleID"];
	$moduleTitle = $row2["moduleTitle"];


	// reads record and checks appropriate box
	$sqlCheck = mysql_query("SELECT * FROM coursemodule WHERE courseID = '".$prodID."' AND moduleID = '".$moduleID."'") or die(mysql_error());
	$count = mysql_num_rows($sqlCheck); //count number of results returned
	if($count > 0){
		$checked = 'checked = "checked"';			
	}
	else
	{
		$checked = "";
	}
	//

	//creates the checkboxes
	$category_list .= '<input type="checkbox" name="module[]" id="module[]" value="'.$moduleID.'" '.$checked.'/> <input type="checkbox" name="core['.$moduleID.']" value="'.$isCore.'" '.$checked.'/>'.$moduleTitle.' ';

	//echo "The result: ".$checked."<br>";		
}

} else { 
$Category_list = "Error: Could not find any modules";
}
echo '<p>'.$category_list.'</p>';

?> 


 

If you have any ideas then please let me know.

 

Thanks

 

Link to comment
Share on other sites

well, yes, if that's the condition you want,

 

if($count > 0 && $isScore == 1){
$checked = 'checked = "checked"';			
}else{
$checked = "";
}

 

(BTW, Why does $_GET['pid'] become $prodID if it's called courseID in the database? You basically have 3 different names for the same value, that makes your code harder to read and could easily lead to mistakes.)

 

Something to try: try this little exercise: do a simple database query, grabbing just one row (with limit 1), use mysql_fetch_array and print_r() to view the results. then do the same but use mysql_fetch_assoc instead of mysql_fetch_array. Compare both results. Cool huh? I almost never use mysql_fetch_array.

 

also:

 

while($result = mysql_fetch_assoc($query)){
   //... do something
}

 

will only work while there are rows being pulled out. if the query returns empty, the code in the while loop will never be executed. With this in mind, what is the point of always doing mysql_num_rows($query) before each database call? you're basically querying the database twice every time.

 

The best way to do things is to adjust your code to the 'most likely event'... meaning:

if it's most likely that your database will be empty, you can check it first. Otherwise don't bother, since most of the times it won't be necessary.

 

 

Link to comment
Share on other sites

  • 2 weeks later...

Hi,

 

Thanks for your help, have not got round to work on this and get back in touch with you. Sorry.

 

The working code that was used is below:


if($modCount > 0){
while($row2 = mysql_fetch_array($result2)){
	$moduleID = $row2["moduleID"];
	$moduleTitle = $row2["moduleTitle"];

	// reads record and checks appropriate boxes
	$sqlCheck = mysql_query("SELECT * FROM coursemodule WHERE courseID = '".$courseID."' AND moduleID = '".$moduleID."'") or die(mysql_error());			
	$count = mysql_num_rows($sqlCheck); //count number of results returned

	$coreCourse = mysql_fetch_array($sqlCheck);		// retrievs results from the sql array
	$isCore = $coreCourse['iscore'];				// retrieves iscore value from the array		

	$checked1 = "";									// set these initially as blank to avoid errors
	$checked2 = "";

	// checks value and ticks box		
	if($count > 0){
		$checked1 = 'checked = "checked"';			
	}else{
		$checked1 = "";
	}

	if($isCore > 0){
		$checked2 = 'checked = "checked"';			
	}else{
		$checked2 = "";
	}

//creates the checkboxes
$category_list .= '<input type="checkbox" name="module[]" id="module[]" value="'.$moduleID.'" '.$checked1.'/> <input type="checkbox" name="core['.$moduleID.']" value="" '.$checked2.'/>'.$moduleTitle.' ';	

 

Ok, now that I have populated the checkboxes when you click to edit a course I have now been now been trying to work out the code when you try to submit the edited course.

 

Below is the code that does work and allows you to untick a module and select another module or add more modules to link to the course. Only problem is the isCore value for the 2nd checkbox is not working. I have added the isCore part but it does not seem to work correctly, taking this part out works fine but obviously would not set the iscore value to either 1 or 0.

 

<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form2")) {
  $updateSQL = sprintf("UPDATE courses SET courseTitle=%s WHERE courseID=%s",
                       GetSQLValueString($_POST['courseTitle'], "text"),
                       GetSQLValueString($_POST['courseID'], "int"));

  mysql_select_db($database_module_system, $module_system);
  $Result1 = mysql_query($updateSQL, $module_system) or die(mysql_error());

  $updateGoTo = "course_list.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form4")) {
  $updateSQL = sprintf("UPDATE courses SET courseTitle=%s WHERE courseID=%s",
                       GetSQLValueString($_POST['courseTitle'], "text"),
                       GetSQLValueString($_POST['courseID'], "int"));

  mysql_select_db($database_module_system, $module_system);
  $Result1 = mysql_query($updateSQL, $module_system) or die(mysql_error());
  
  //SQL for course modules, !!!updates both entries to the same cat id
$prodID = $_POST['courseID'];
// first deletes any entries already in the table for the courseID
$sqlDelCat = mysql_query("DELETE FROM coursemodule WHERE courseID='$prodID'") or die (mysql_error());
// then uploads new selections
$cats_upload = "";
  foreach($_POST['module'] as $cats) // errors if no modules are selected
  
  //
  	if( isset($_POST['core'][$cats]) ){



$isCore = 1;
}else{
   $isCore = 0;
}


echo $prodID.' - '.$cats.' - '.$isCore.'<br>';

{

$query2 = "INSERT INTO coursemodule (courseID, moduleID, iscore) VALUES ('".$prodID."','".$cats."','".$isCore."')";
   $result2 = mysql_query($query2);
//
  



   if ($result2) {
//    echo mysql_affected_rows()." record uploaded successfully.<br>";
    $cats_upload = $cats_upload + mysql_affected_rows(); // counts how many rows affected
   }
   else
   {
    echo "an error has occurred uploading to the coursemodule database.<br>";
   } 

  }
  
  
}

$colname_courses = "-1";
if (isset($_GET['pid'])) {
  $colname_courses = $_GET['pid'];
}
mysql_select_db($database_module_system, $module_system);
$query_courses = sprintf("SELECT * FROM courses WHERE courseID = %s", GetSQLValueString($colname_courses, "int"));
$courses = mysql_query($query_courses, $module_system) or die(mysql_error());
$row_courses = mysql_fetch_assoc($courses);
$totalRows_courses = mysql_num_rows($courses);
?>

 

Please let me know on what the best way around this is.

 

Thanks

 

Link to comment
Share on other sites

  • 3 weeks later...
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.