Jump to content

More checkbox array problems


bulrush

Recommended Posts

Problem: my checkbox array chkBrand[] is not saving data when I click the save button called cmdSave. Each checkbox specifies a brand connected to a model number. Multiple brands can be connected to each model number. (Don't ask, it's what the customer wants.)

 

So, if I check the checkbox in row 0 and row 3, only row 0 shows up. If I check the boxes in row 0, 1, 5, only rows 0, 1 show up in chkBrand and $newchkbrandarr.

 

First, my routine to see which button is checked is at the top of the php file. Here it is.

else if (isset($_POST['cmdSave'])) //Try to save items first.
    {
$newchkbrandarr=$_POST['chkBrand']; //Checkbox for each brand.
$oldchkbrandarr=$_SESSION['oldchkbrandarr'];
$olddata=$_SESSION['olddata']; //Non-brand Fields strung together.
$brandlist=$_SESSION['brandlist']; //List of brands displayed.

crPrintarr('chkBrand raw',$_POST['chkBrand']); //DEBUG. Prints array to screen.
//===At this point chkBrand[] contains: 1

//Turn nulls in checkboxes to zeros.
$cnt=count($newchkbrandarr);
for ($j=0; $j<$cnt; $j++)
	{
	$newchkbrandarr[$j]=$newchkbrandarr[$j]+0;
	} //for j

//Make sure that at least one brand is checked.
$cnt=count($newchkbrandarr);
crPrintarr('newchkbrandarr',$newchkbrandarr); //DEBUG
//===At this point, $newchkbrandarr contains: 1, 0

$s='Elements in newchkbrandarr cnt='.$cnt;
$s.=', count brandlist='.count($brandlist);
crDebug($s); //DEBUG
$cnt2=0;
$cnt=count($newchkbrandarr); //Find number of elements.
for ($j=0; $j<$cnt; $j++)
	{
	$cnt2=$cnt2+$newchkbrandarr[$j]+0;
	//$s='arrpos '.$j.': newchkbrandarr='.($newchkbrandarr[$j]+0).', cnt2='.$cnt2;
	//crDebug($s); //DEBUG
	} # for j

 

Here is my code to construct the array of checkboxes, one per table row. Each checkbox has its array position explicitly defined as $x. $x starts at zero, and is incremented by 1 for each table row (each check box).

 

    $x=0;
    while ($row = mysqli_fetch_array($result)) 		
    	{
$br=trim($row['brand']); //Brand name to display
$brandvar=$br;
$brandlist[]=$br; //Save every found brand for later.
//First find if brand is checked on table "brands". 
        $query2 = "SELECT brand ".
        "FROM brands ".
        "WHERE ".
        "(partid=".$partidvar.") ".
        "AND (brand='".$br."') ".
        "ORDER BY brand ".
        ";";
        $cntchk=crqryCount($query2,false); //If $cntchk>0 then brand is checked.
        //$s="Is brand stored already? <br/>$query2";
        //crDebug($s); //DEBUG
        
        $query2 = "SELECT brand ".
        "FROM zzbrands ".
        "WHERE (brand='".$br."') ".
        "AND (prodnameoverride=1) ".
        "ORDER BY brand ".
        ";";
	$override=crqryCount($query2,false); //Can this brand override product name?

	$s="\n";
    	$s.='<tr><td>'.
    	    '<input type="text" value="'.$br.'" id="txtBrand[]" name="txtBrand[]" '.
    	    'size="20" readonly class="mydisabled" />';
    	$s.='<td align="center">';
    	$s.='<input type="checkbox" name="chkBrand['.$x.']" '.
    	    'id="chkBrand['.$x.']" value="1" ';
    	if ($cntchk>0)
    		{
    		$s.='checked="checked" ';
    		$oldchkbrandarr[$x]=1;
    		}
    	else {
    		$oldchkbrandarr[$x]=0;
    		}
    	$s.='/>';

 

Any ideas what I might be missing?

 

Link to comment
https://forums.phpfreaks.com/topic/212374-more-checkbox-array-problems/
Share on other sites

Sorry I didn't show you that, but at the bottom of the WHILE loop that creates the checkboxes, the $x does get incremented for each row, and each checkbox is in a different array position, going from chkBrand[0] to chkBrand[8].

 

Here is a partial <FORM> showing how the chkBrand[] is numered.

<form action="/toolbox/training/masttest/editpart.php?" method="post"><hr/>Commands: <input type="submit" name="cmdSave" value="Save" title="Save all changes on this screen" /> <hr/><b>Check one or more brands: (Do bullet delete, reorder before doing pricing screen)</b>
<table border=1 style="border: 2px solid red;border-collapse:collapse">
<tr valign="bottom"><th>Check box<br/>to enable brand<th>Enable brand?<th>Brand pricing<th>Brand bullets<th>Copy bullets from another brand<th>Override<br/>product name</tr>

<tr><td><input type="text" value="brand1" id="txtBrand[]" name="txtBrand[]" size="20" readonly class="mydisabled" /><td align="center"><input type="checkbox" name="chkBrand[0]" id="chkBrand[0]" value="1" checked="checked" /><td>Edit pricing<td><a href="editbullets.php?partid=23280&brand=brand1&model=abc100&prodcat=aaChuckProdcat">Edit bullets (0)</a><td>
<td></tr>

<tr><td><input type="text" value="brand2" id="txtBrand[]" name="txtBrand[]" size="20" readonly class="mydisabled" /><td align="center"><input type="checkbox" name="chkBrand[1]" id="chkBrand[1]" value="1" /><td><td><td>
<td></tr>

<tr><td><input type="text" value="brand3" id="txtBrand[]" name="txtBrand[]" size="20" readonly class="mydisabled" /><td align="center"><input type="checkbox" name="chkBrand[2]" id="chkBrand[2]" value="1" /><td><td><td>
<td></tr>

<tr><td><input type="text" value="brand4" id="txtBrand[]" name="txtBrand[]" size="20" readonly class="mydisabled" /><td align="center"><input type="checkbox" name="chkBrand[3]" id="chkBrand[3]" value="1" /><td><td><td>
<td></tr>

</table>
</form>

OK

when you check rows 0, 1 and 5 in variable $newchkbrandarr is array(0 = >1, 1 => 1, 5 =>1) is it righr?

after 1st for loop $newchkbrandarr is array(0 = >1, 1 => 1, 2 => 0, 5 =>1) is it right?

in 2nd for loop you sum this array $cnt2 is 3

 

can you explain what you want?

Ok. Things seem to be working now. My app has its own login and user system. The only thing I did different was I logged off last night, and logged into my app this morning, and the variable $newchkbrandarr appears to be storing the values correctly and passing them to the cmdSave routine in the same php file.

 

I was using IE 8.0. I wonder if it's a bug with IE 8.0. Yesterday I did close all my IE windows, then restart them but I never logged out of my app. When I went back to my app's page, I was still logged into my app.

 

Anyway, $newchkbrandarr is an array that is supposed to reflect the checkmarks stored in chkBrand[], so I can tell if I need to add a new brand to a model (a checkmark was added) or delete a brand from a model (checkmark was unchecked). It wasn't working yesterday, now it is.

 

Thanks!

 

I spoke too soon. Sometimes $newchkbrandarr has the correct values, sometimes not. Let's say I start with chkBrand[] boxes 0, 1, and 4 checked. I click cmdSave to start my save routine in the same php file. I created my own routine to print an array, called crPrintarr. Here's what $newchkbrandarr starts off as:

pos 0=1

pos 1=1

pos 2=0

pos 3=0

pos 4=1

 

These values are all correct. Now if I check the box for chkBrand number 7, I get these values in $newchkbrandarr:

pos 0=1

pos 1=1

pos 2=0

pos 3=0

pos 4=1

 

Noticed that positions 5, 6, and 7 don't even appear in the array! Pos 7 should be 1 (indicating the checkbox chkBrand was checked).

 

Here is my code at the beginning of where cmdSave starts:

else if (isset($_POST['cmdSave'])) //Try to save items first.
    {
$partidvar=trim($_POST['txtPartid']);
$modelnumvar=trim(crProcmodelnum($_POST['txtModelnum']));
$modelnumvar=strtoupper($modelnumvar);
$_SESSION['modelnum']=$modelnumvar; //Save for form display.
$modelnumcatvar=trim(crProcprodname($_POST['txtModelnumcat']));
$newpartvar=$_POST['chkNewpart']; //from checkbox to mark part as NEW
$prodcatvar=trim($_POST['cbxProdcat']);
$prodnamevar=trim(crProcprodname($_POST['txtProdname']));
$prodsubnamevar=trim(crProcprodname($_POST['txtProdsubname']));
$footnotevar=$_POST['chkFootnote']+0;
$newchkbrandarr=$_POST['chkBrand']; //Checkbox for each brand.
$oldchkbrandarr=$_SESSION['oldchkbrandarr']; //Checkboxes before user changed them.
$olddata=$_SESSION['olddata']; //Non-brand Fields strung together.
$brandlist=$_SESSION['brandlist']; //List of brands displayed.

crPrintarr('chkBrand raw',$_POST['chkBrand']); //DEBUG

//Turn nulls in checkboxes to zeros.
$cnt=count($newchkbrandarr);
for ($j=0; $j<$cnt; $j++)
	{
	$newchkbrandarr[$j]=$newchkbrandarr[$j]+0;
	} //for j
$newdata=$partidvar.$modelnumvar.$prodcatvar.$prodnamevar.
         $prodsubnamevar.$newpartvar.$modelnumcatvar.$footnotevar.$modelnumcatvar;

    $prodcatvar=($prodcatvar);
    $prodnamevar=crTitlecase($prodnamevar);
    $prodsubnamevar=crTitlecase($prodsubnamevar);

//Make sure that at least one brand is checked.
$cnt=count($newchkbrandarr);
crPrintarr('newchkbrandarr',$newchkbrandarr); //DEBUG, params are header to display, and array var
$s='Elements in newchkbrandarr cnt='.$cnt;
$s.=', count brandlist='.count($brandlist);
crDebug($s); //DEBUG
$cnt2=0;
$cnt=count($newchkbrandarr); //Find number of elements.
for ($j=0; $j<$cnt; $j++)
	{
	$cnt2=$cnt2+$newchkbrandarr[$j]+0;
	//$s='arrpos '.$j.': newchkbrandarr='.($newchkbrandarr[$j]+0).', cnt2='.$cnt2;
	//crDebug($s); //DEBUG
	} # for j
if ($cnt2==0)
	{
        $msg='ERROR: at least one brand should be checked. Please choose one. ';
        $msg.='cnt2='.$cnt2;
        crError($_SERVER['PHP_SELF'].' line '.__LINE__,$msg,true);
	}


And here is crPrintarr:

function crPrintarr($hdr,$arr,$lend='<br/>')
/* Print an array to the screen. 
$hdr=info about array we are displaying
$arr=array
$lend=line ending
*/ 
{
$cnt=count($arr);
$s='crPrintarr: '.$hdr.'<br/>';
for ($i=0; $i<$cnt; $i++)
{
$s.='--pos '.$i.'='.$arr[$i].'<br/>';
} //for i
crDebug($s);
return;
}

change

else if (isset($_POST['cmdSave'])) //Try to save items first.
    {
$partidvar=trim($_POST['txtPartid']);
$modelnumvar=trim(crProcmodelnum($_POST['txtModelnum']));
$modelnumvar=strtoupper($modelnumvar);
$_SESSION['modelnum']=$modelnumvar; //Save for form display.
$modelnumcatvar=trim(crProcprodname($_POST['txtModelnumcat']));
$newpartvar=$_POST['chkNewpart']; //from checkbox to mark part as NEW
$prodcatvar=trim($_POST['cbxProdcat']);
$prodnamevar=trim(crProcprodname($_POST['txtProdname']));
$prodsubnamevar=trim(crProcprodname($_POST['txtProdsubname']));
$footnotevar=$_POST['chkFootnote']+0;
$newchkbrandarr=$_POST['chkBrand']; //Checkbox for each brand.
$oldchkbrandarr=$_SESSION['oldchkbrandarr']; //Checkboxes before user changed them.
$olddata=$_SESSION['olddata']; //Non-brand Fields strung together.
$brandlist=$_SESSION['brandlist']; //List of brands displayed.

crPrintarr('chkBrand raw',$_POST['chkBrand']); //DEBUG

//Turn nulls in checkboxes to zeros.
$cnt=count($newchkbrandarr);
for ($j=0; $j<$cnt; $j++)
	{
	$newchkbrandarr[$j]=$newchkbrandarr[$j]+0;
	} //for j
$newdata=$partidvar.$modelnumvar.$prodcatvar.$prodnamevar.
         $prodsubnamevar.$newpartvar.$modelnumcatvar.$footnotevar.$modelnumcatvar;

to

 else 	$footnotevar=$_POST['chkFootnote']+0;
$newchkbrandarr=$_POST['chkBrand']; //Checkbox for each brand.
$oldchkbrandarr=$_SESSION['oldchkbrandarr']; //Checkboxes before user changed them.
$olddata=$_SESSION['olddata']; //Non-brand Fields strung together.
$brandlist=$_SESSION['brandlist']; //List of brands displayed.

//	crPrintarr('chkBrand raw',$_POST['chkBrand']); //DEBUG

//Turn nulls in checkboxes to zeros.
//$cnt=count($newchkbrandarr);
        $cnt = max(array_keys($newchkbrandarr));
for ($j=0; $j<=$cnt; $j++)
	{
	//$newchkbrandarr[$j]=$newchkbrandarr[$j]+0;
                if (!isset($newchkbrandarr[$j])) $newchkbrandarr[$j]=0;
	} //for j
$newdata=$partidvar.$modelnumvar.$prodcatvar.$prodnamevar.
         $prodsubnamevar.$newpartvar.$modelnumcatvar.$footnotevar.$modelnumcatvar;

Thanks, sasa. I did some work over the weekend and apparently the count() function does not work properly for an array of checkboxes. So I must keep track of how many checkboxes there are, and loop through them using that variable.

 

Below is a complete test program which illustrates the fix. Let's call it tstchk.php. It does not require any connection to any database.

<?php session_start(); 
//require_once('connectvars.php');
//require_once('constants.php');
//require_once('crutil.php');
$title='Checkbox test v.12a';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <?php 
  echo '<title>'.$title.'</title>';
  ?>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<?php
//require_once('navmenu.php');
echo '<h2>'.$title.'</h2>';
echo '<p>Testing check box array. Check some boxes then click the Save button. The value of each entry in the checkbox array will then be printed. ';
echo 'If you check boxes 0, 1, and 4, only the values for boxes 0, 1 and 4 SHOULD be set to 1 (indicating checked). However, what happens is, only  the values for entries 0 and 1 are 1 (indicating checked). ';
echo '<br/>';
?>

<!-- comment -->
<?php
define("MAXCHECKBOX","9");
// Connect to the database 
//$dbc = mysqli_connect($host, $user, $password, $database);
$oldbrandarr=$_SESSION['oldbrandarr'];

$brandarr=array();
$brandarr=$_POST["chkBrand"];

if (isset($_POST['cmdSave'])) //Save records that were changed.
    {
    echo '<hr/>';
   	//$arrcnt=count($brandarr);
$arrcnt=MAXCHECKBOX;
for ($i=1; $i<$arrcnt; $i++)
	{
	if ((is_null($brandarr[$i])) or (empty($brandarr[$i])) )
		{$brandarr[$i]=0;
		}
	else {
		$brandarr[$i]=$brandarr[$i]+0;
		}
	$s='box '.$i.'='.$brandarr[$i].'<br/>';
	echo "$s\n";
        } //for i
    echo '<hr/>';
    foreach ($brandarr as $b)
    	{
    	echo "$b<br/>";
    	}
    echo '<hr/>';
    } //if isset($_POST['cmdSave']

?>

<!-------------------------------------------------------->
<form action="<?php echo $_SERVER['PHP_SELF'].'?'.SID; ?>" method="post">
<?php
//$oldbrandarr=array(); //Init array.
echo "<table>\n";
for ($i=1; $i<=MAXCHECKBOX; $i++)
	{
	$s='<tr><td>Box '.$i.' <input type="checkbox" name="chkBrand['.$i.']" '.
	   'id="chkBrand['.$i.']" value="1" />';

	/* $s='<tr><td>Box '.$i.' <input type="checkbox" name="chkBrand[]" '.
	   'id="chkBrand[]" value="1" />';
	*/
	echo "$s</tr>\n";
	} // for i
echo '</table>'."\n";

//$_SESSION['oldbrandarr']=$oldbrandarr; //Save for use above in this file.
?>

<p>
<p>Commands: <input type="submit" name="cmdSave" value="Save" />
</form>

</body>
</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.