Hide form checkbox

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
troutmissile
Forum Newbie
Posts: 7
Joined: Mon Feb 07, 2011 5:16 pm

Hide form checkbox

Post by troutmissile »

Hello,

I'm a big fat noob learning how to use mysql the stupid way, by trial and error, and by staring at the screen until something clicks.

I have a table with

id next_id bowl (INT) dish (INT)
_____________________________

1 4
2 1
3 2
4 3


All 4 users are admin level, so when any user checks one of the boxes and clicks its "Done" button, their bowl or dish field variable is set to '0', AND the user whose id is 'next_id' has his bowl or dish variable set to '1'.

It works, but it is possible for a user to click the box and hit the "Done" button even when it echoes "You are done," and there is no reason for them to, which sets the next user's bowl or dish variable to '1' before it should be.

What I would like to do is have the checkbox with value <?php echo $rrows['id']; ?> be hidden when the logged-in user's 'bowl' (or 'dish') variable is '0', and visible when it is '1'.

I have searched around and read that it might be possible to use a "PHP session variable check (with an "if" statement) to add style="display:none;" to the tag when that element should be hidden."

Does that sound like the best way? Would that be if($_SESSION... ?

What about an if empty()... ? But where would that go, and what would it look like?

Below is the code, with some formatting tags removed, which I hope will make it quicker to read through.

Thanks for any clues!

Code: Select all

<?php 
include 'dbc.php';
page_protect();

if(!checkAdmin()) {
header("Location: login.php");
exit();
}

$page_limit = 10; 


$host  = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = @ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path   = rtrim($login_path, '/\\');

// filter GET values
foreach($_GET as $key => $value) {
	$get[$key] = filter($value);
}

foreach($_POST as $key => $value) {
	$post[$key] = filter($value);
}


if($_POST['doApprove'] == 'Done') {

if(!empty($_POST['u'])) {
	foreach ($_POST['u'] as $uid) {
		$id = filter($uid);
		
list($next_id) = mysql_fetch_row(mysql_query("select next_id from users where id='$id'"));	

mysql_query("update users set approved='1' where id='$id'");
					
mysql_query("update users set next='1' where id='$next_id'");

mysql_query("update users set next='0' where id='$id'");
		
list($to_email) = mysql_fetch_row(mysql_query("select user_email from users where id='$uid'"));	

$message = 
"Hello.\n


";

@mail($to_email, "Subject", $message,
    "From: \"Me\" <auto-reply@$host>\r\n" .
     "X-Mailer: PHP/" . phpversion()); 
	 
	}
 }
 
 $ret = $_SERVER['PHP_SELF'] . '?'.$_POST['query_str'];	 
 header("Location: $ret");
 exit();
}


if($_POST['doDish'] == 'Done') {

if(!empty($_POST['u'])) {
	foreach ($_POST['u'] as $uid) {
		$id = filter($uid);

list($next_id) = mysql_fetch_row(mysql_query("select next_id from users where id='$id'"));	

mysql_query("update users set approved='1' where id='$id'");
					
mysql_query("update users set next='1' where id='$next_id'");

mysql_query("update users set next='0' where id='$id'");
		
list($to_email) = mysql_fetch_row(mysql_query("select user_email from users where id='$uid'"));	

$message = 
"Hello.\n
";

@mail($to_email, "Subject", $message,
    "From: \"Me\" <auto-reply@$host>\r\n" .
     "X-Mailer: PHP/" . phpversion()); 
	 
	}
 }
 
 $ret = $_SERVER['PHP_SELF'] . '?'.$_POST['query_str'];	 
 header("Location: $ret");
 exit();
}

$rs_all = mysql_query("select count(*) as total_all from users where id='$id'") or die(mysql_error());
$rs_active = mysql_query("select count(*) as total_active from users where approved='1'") or die(mysql_error());
$rs_total_pending = mysql_query("select count(*) as tot from users where id='$id'");						   

list($total_pending) = mysql_fetch_row($rs_total_pending);
list($all) = mysql_fetch_row($rs_all);
list($active) = mysql_fetch_row($rs_active);

?>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="styles.css" rel="stylesheet" type="text/css">
<script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

</head>

<body>

      <table width="80%" border="0" align="center" cellpadding="10" cellspacing="0">
        <tr>
          <td><form name="form1" method="get" action="admin.php">           
                <input type="radio" name="qoption" value="pending">
                Show my stuff
                <input name="doSearch" type="submit" id="doSearch2" value="List">
              </form></td>
        </tr>
      </table>
  
        <?php if ($get['doSearch'] == 'List') {
	  if($get['qoption'] == 'pending') {
	  $cond = "where `id`='$_SESSION[user_id]'";
	  }
	 
	  
	  if($get['qoption'] == 'pending') { 
	  $sql = "select * from users $cond"; 
	  } 
	  else { 
	  $sql = "select * from users where `id` = '$_SESSION[user_id]'";
	  }

	  
	  $rs_total = mysql_query($sql) or die(mysql_error());
	  $total = mysql_num_rows($rs_total);
	  
	  if (!isset($_GET['page']) )
		{ $start=0; } else
		{ $start = ($_GET['page'] - 1) * $page_limit; }
	  
	  $rs_results = mysql_query($sql . " limit $start,$page_limit") or die(mysql_error());
	  $total_pages = ceil($total/$page_limit);
	  
	  ?>
    
        <?php 
	  
	  // outputting the pages
		if ($total > $page_limit)
		{
		echo "<div><strong>Pages:</strong> ";
		$i = 0;
		while ($i < $page_limit)
		{
		
		
		$page_no = $i+1;
		$qstr = ereg_replace("&page=[0-9]+","",$_SERVER['QUERY_STRING']);
		echo "<a href=\"admin.php?$qstr&page=$page_no\">$page_no</a> ";
		$i++;
		}
		echo "</div>";
		}  ?>
	  </p>
		<form name "searchform" action="admin.php" method="post">
        
          <?php while ($rrows = mysql_fetch_array($rs_results)) {?>
     <span id="approve<? echo $rrows['id']; ?>">
              <?php if(!$rrows['next']) { echo "You are done"; } else {echo "You must check this box and hit the Done button"; }?>
            </span>
            <input name="u[]" type="checkbox" value="<?php echo $rrows['id']; ?>" id="u[]">
           <input name="doApprove" type="submit" id="doApprove" value="Done">
            <input name="query_str" type="hidden" id="query_str" value="<?php echo $_SERVER['QUERY_STRING']; ?>"><span id="approve<? echo $rrows['id']; ?>">
              <?php if(!$rrows['dish']) { echo "You are done"; } else {echo "You must check this box and hit the Done button"; }?>
            </span>
            <input name="u[]2" type="checkbox" value="<?php echo $rrows['id']; ?>" id="u[]2"></td>
            <input name="doDish" type="submit" id="doDish" value="Done">
            <input name="query_str2" type="hidden" id="query_str2" value="<?php echo $_SERVER['QUERY_STRING']; ?>">
          <?php } ?>
	    
        </form>
		
	
	  <?php } ?>
     

</body>
</html>
gooney0
Forum Commoner
Posts: 56
Joined: Fri Jan 21, 2011 1:40 pm
Location: Reston, VA

Re: Hide form checkbox

Post by gooney0 »

There are a few ways to do this.

First off I would make or find a variable that holds the status. Here is an example:

// Form was submitted and was successful
$_SESSION["youaredone"] =1;


// Now when displaying the form

<input name="u[]2" type="checkbox" value="<?php echo $rrows['id']; ?>" id="u[]2" <?php
if(!$_SESSION["youaredone"])
{
echo " style=\"display: none;\"; ";
}?>
>

Other ideas:

You could also use javascript to change the style of that element.

Use PHP to not even output the element, or output a <input type=hidden> element instead.

Remember that the $_SESSION array carries over from page to page. That may not be what you want.

Tip: Plan your $_SESSION array with a little care. If your array keys are too generic it'll get confusing for you latter.
troutmissile
Forum Newbie
Posts: 7
Joined: Mon Feb 07, 2011 5:16 pm

Re: Hide form checkbox

Post by troutmissile »

Sorry I did not reply sooner! I think I got sucked into a programming vortex of some kind. I'm just getting used to how absorbing it is. Thank you so much for the help. I realized I had the variable right in front of me: $rrows['next'], and echo " style=\"display: none;\"; "; worked with it just as you said. I would have grown old before I figured out that second semicolon.

So everything works now, and I would like to make it so users populate certain fields, including 'next_id', programmatically when they register, so that it would be

id next_id
_________

1 4
2 1
3 2
4 3

where id is auto-increment and next_id would reflect a reordering of id. And registrations would have to be done for groups (of four, for this example), not individual users, somehow, so that each group had its own table, I guess.

What do you think-- given I have made it this far, should even I try it without training?

If training, any recommendations?

Thanks again for that echo code-- I really appreciate it!


Edit-- Actually, I think I might see another way, without new tables, much simpler-- just make users register under a single group name, which will then be get-able in the ($get['doSearch'] == 'List') part. Love php.
gooney0
Forum Commoner
Posts: 56
Joined: Fri Jan 21, 2011 1:40 pm
Location: Reston, VA

Re: Hide form checkbox

Post by gooney0 »

Training doesn't hurt, but there is no replacement for doing. I'd say continue.

Everyone has their own style but here are a few tips based on mine:

95% of programming is logic. If your logic is simple and clean the rest is just looking up syntax and which function to use.

Start programming with just comments. Afterward go back and fill in code.

Example:

// Get users from database
// if users exist

// Show number of users

// output users in a table

// Remove user button

Now that the logic is laid out we can simply it with functions. We don't have to, but it will get complicated if our logic gets too long winded.

I like lots of functions and short programs. It's so much easier to add features or fix bugs that way.

In this example i'd have functions like:

get_users()
output_users($users)
output_user_row($user)

Now our pretend code looks something like:

// Get users from database
$users=get_users();
// if users exist
if($users)
{
// Show number of users
print count($users);
// output users in a table
output_users($users);
// Remove user button (this is now handled by the output_users function which will call the output_user_row function

} else {
echo "ain't no users";
}
troutmissile
Forum Newbie
Posts: 7
Joined: Mon Feb 07, 2011 5:16 pm

Re: Hide form checkbox

Post by troutmissile »

Thank you! That is very helpful advice, and so clearly expressed. I really appreciate it. You should be a teacher.

I see what you mean about lots of functions/short programs. It seems like the most direct way to express the logic.
gooney0
Forum Commoner
Posts: 56
Joined: Fri Jan 21, 2011 1:40 pm
Location: Reston, VA

Re: Hide form checkbox

Post by gooney0 »

Looks like it didn't translate but my example was indented. Along with comments this seems to be trivial but really does pay off.

Once you have a lot of html or longer programs you really want to quickly find the end of a loop or if statement. If you put code in the wrong place you'll start pulling your hair out.

I like to add little comments such as:

Code: Select all

if($users)
     {
    // blah blah blah
     foreach($users as $user)
          {
          // do stuff per user
          }  // end foreach users
     } // end if users
I also resist the urge to shorten variable and array names. I find I'm much better off using long, pretty names.

Example:

In my table I have fields:

ID, First Name, Last Name

By using "pretty" names I don't have to translate them or remember that $firstname = "First Name." I can now write pretty code like:

Code: Select all

$fields=array("First Name", "Last Name");
$values=a_function_which_returns_an_array();
foreach($fields as $field)
     {
     print "<input name=\"{$field}\" value=\"{$values[$field]}\" >";
     }
Try to decide on your variables and arrays ahead of time. If I need to work with a list of people I need to decide how to store it. I could use objects, arrays, or a whole lot of variables. Make it clean:

$people[0]["First Name"]="George";
$people[0]["Last Name"]="Washington";
troutmissile
Forum Newbie
Posts: 7
Joined: Mon Feb 07, 2011 5:16 pm

Re: Hide form checkbox

Post by troutmissile »

Thanks again! Yes, keeping track of where statements end is so important. I can't afford to lose any more hair, so I really appreciate the tips!
Post Reply