Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checkbox timing issue 1

Status
Not open for further replies.

RPGguy

Programmer
Jul 27, 2001
73
0
0
US
In the script below I begin with the first checkbox selected. If I check the second box and click the submit button, the parameter list I build does not pick up the second checkbox. Any ideas. Thanks as always for the help.

Scott

<?
$order = "";

if (isset($_POST['first_name']))
$order .= "first_name,";

if (isset($_POST['last_name']))
$order .= "last_name,";

/* remove the final OR */
$order = substr($order, 0, -1);

?>

<html>
<head>

<title>Test Select</title>
</head>

<body>
<form name="form1" method="post" action="activelist.php?vartable=e107_act_emps&varseq=<? print StripSlashes($order); ?>">


<input type="checkbox" name="first_name" value="first_name" CHECKED><br>
<input type="checkbox" name="last_name" value="last_name"><br>
<input type="submit" name="Submit" value="Submit" >
</form>
</body>
</html>
 
I don't understand what you mean by "does not pick up the second checkbox". This modification of your script:

Code:
<?
$order = "";

if (isset($_POST['first_name']))
    $order .= "first_name,";

if (isset($_POST['last_name']))
    $order .= "last_name,";

/* remove the final OR */
     $order = substr($order, 0, -1);

?>

<html>
<head>

<title>Test Select</title>
</head>

<body>
<?php
print $order;
?>
<br>
<form name="form1" method="post" action="test_foo.php?vartable=e107_act_emps&varseq=<? print StripSlashes($order); ?>">


<input type="checkbox" name="first_name" value="first_name" CHECKED><br>
<input type="checkbox" name="last_name" value="last_name"><br>
<input type="submit" name="Submit" value="Submit" >
</form>
</body>
</html>

outputs "first_name,last_name" when both checkboxes are selected.


Want the best answers? Ask the best questions! TANSTAAFL!
 
And if you mean to say that the checkboxes don't maintain their status between successive runs of the script, try this version:

Code:
<?
$order = "";

if (isset($_POST['first_name']))
{
	$order .= "first_name,";
}

if (isset($_POST['last_name']))
{
	$order .= "last_name,";
}

/* remove the final OR */
$order = substr($order, 0, -1);

print '
<html>
<head>
	<title>Test Select</title>
</head>
<body>';

print '[' . $order . ']';

print '
<br>
<form name="form1" method="post" action="test_foo.php?vartable=e107_act_emps&varseq=' . StripSlashes($order) . '">
<input type="checkbox" name="first_name" value="first_name"';

if (isset($_POST['first_name']))
{
	print ' CHECKED ';
}
	
print '><br>
<input type="checkbox" name="last_name" value="last_name"';

if (isset($_POST['last_name']))
{
	print ' CHECKED ';
}

print '><br>
<input type="submit" name="Submit" value="Submit" >
</form>
</body>
</html>';
?>


Want the best answers? Ask the best questions! TANSTAAFL!
 
Thanks to all for their help. After researching this it seems that an array and the use of 'explode' are the best way to go.
 
I'm sorry but I can't get this to work. I tried pasting the code from sleipnir214 but when I check a box and click sumbit I go straight to the URL:

Nothing is passed after the 'varseq' parameter and the value of $order is never printed.

Can someone give me a sample script that does this:
Display 2 checkboxes
Click sumbit and go to a new page (say 'test_foo.php' and pass the values of whatever check boxes are selected.

I don't need to print the values as long as they are passed to the 'test_foo.php' page.

Thanks.
 
Code:
[red]Create Form[/red]
<form action=this.php method=get>
<input type=checkbox name="items[blue][][/blue]" value="First"> 
<input type=checkbox name="items[blue][][/blue]" value="Second">
<input type=submit name=submit>
</form>
[red]checkbox names have "[" and "]" added at the end to create an array when the values get passed to the php page[/red]

<?

if(isset($_GET['submit'])){ 
[green]//check that the from was actually submitted by testing the button variable.[/green]

[green]Check if there was more than one checkbox checked.[/green]
if(count($_GET['items'])>1){
[green]echo values from checkboxes[/green]
echo "Values passed were:". $_GET['items'][0] . "AND" . $_GET['items'][1];
}
[green]if only one item was selected display it.[/green]
else{ echo $items[0] ." Only one item was selected";
}
}

Hope this helps you.

----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Thanks but I wasn't clear on my objective. I will display field names available to select in an SQL statement. The user can check which fields they want to see. When they click 'Submit' I want to pass a parm that contains only the field names of the boxes they checked. The action should look like:

selemps.php?sel=last_name,first_name

The next page will execute the SQL using $sel for the selection criteria. The SQL part is no problem. I just can't get the parameter to work. I assume the explode function would work well here.

If I can get 1 example to do this I'll be off to the races. Right now it's very frustrating.

Thanks for eveyone's help thus far.

Scott
 
RPBGuy

below is some code that should give you an example of how to handle this kind of problem. just cut and paste it into a blank web page, provide the db connection data at the top of the file and the table that you want to check the fields for. the code will automatically generate the checkboxes, validate any input and fill an array of validated selections.

let us know if you have any problems with it.

Code:
<?
$table = "";//enter table name
mysql_connect("","","") or die(mysql_error());
mysql_select_db("") or die(mysql_error());

$result = mysql_query("Show fields from $table") or die (mysql_error());
$checkboxes = "";
while ($row = mysql_fetch_assoc($result)):
	$fields[] = $row['Field'];
endwhile;
foreach ($fields as $field):
		if(isset($_POST['cb_fields'])):
			$checked = in_array($field, $_POST['cb_fields']) ? "checked" : "";
		else:
			$checked="";
		endif;
		$checkboxes .= "<tr><td><input $checked type=\"checkbox\" name=\"cb_fields[]\" value=\"{$field}\"/></td><td>{$field}</td></tr>";
endforeach;
echo "<form action=\"{$_SERVER['PHP_SELF']}\" method=\"post\">";
echo "<table>";
echo $checkboxes;
echo "<tr><td></td><td><input type=\"submit\" name=\"submit\" value=\"submit\"></td></tr></table>";
echo "</form>";

if (isset($_POST['submit'])):	//is form submitted
	if (isset($_POST['cb_fields']) && is_array($_POST['cb_fields'])):  //where any checkboxes pressed
		
		//validate that each item is an actual field and we don't have sql injection here
		foreach ($_POST['cb_fields'] as $cb_fld):
			if (in_array($cb_fld, $fields)):
				$validfield[] = $cb_fld;
			endif;
		endforeach;
		echo "<br/>We now have an array of selected fields that are validated<pre>";
		print_r($validfield);
		echo "</pre>";
	else:
		//do nothing
	endif;
else:
	//do nothing	
endif;
?>
 
That is brilliant. I'm pretty new at this so could you possibly show me 2 modifications to your code?

1) Can you display the database fields as a table with a few columns per row?

2) What would the form action look like if I want to pass the $validfield array to another script and how does the second script retrieve the values.

I'm an old mainframe programmer that appreciates smart code and this is impressive.
 
backwards ...:

to make it into two files. This is kind of straightforward and kind of not. to keep the flow working we're going to need to introduce sessions here.

File1 - the form
form.php
Code:
session_start();
$table = "";//enter table name
mysql_connect("","","") or die(mysql_error());
mysql_select_db("") or die(mysql_error());

$result = mysql_query("Show fields from $table") or die (mysql_error());
$checkboxes = "";
while ($row = mysql_fetch_assoc($result)):
    $fields[] = $row['Field'];
endwhile;
foreach ($fields as $field):
        if(isset($_SESSION['cb_fields'])):
            $checked = in_array($field, $_SESSION['cb_fields']) ? "checked" : "";
        else:
            $checked="";
        endif;
        $checkboxes .= "<tr><td><input $checked type=\"checkbox\" name=\"cb_fields[]\" value=\"{$field}\"/></td><td>{$field}</td></tr>";
endforeach;
echo "<form action=\"page2.php\" method=\"post\">";
echo "<table>";
echo $checkboxes;
echo "<tr><td></td><td><input type=\"submit\" name=\"submit\" value=\"submit\"></td></tr></table>";
echo "</form>";

and page2.php (the processing page)
Code:
session_start();
ob_start(); //use output buffering just in case we hit an error event and need to go back to the old page.

if (isset($_SESSION['cb_fields'])):
  unset($_SESSION['cb_fields']); //cancel any existing session variable
endif;

$table = "";//enter table name
mysql_connect("","","") or die(mysql_error());
mysql_select_db("") or die(mysql_error());

$result = mysql_query("Show fields from $table") or die (mysql_error());
$checkboxes = "";
while ($row = mysql_fetch_assoc($result)):
    $fields[] = $row['Field'];
endwhile;

if (isset($_POST['submit'])):    //is form submitted
    if (isset($_POST['cb_fields']) && is_array($_POST['cb_fields'])):  //where any checkboxes pressed
        
        //validate that each item is an actual field and we don't have sql injection here
       //set the session variable
        $_SESSION['cb_fields'] = $_POST['cb_fields'];

        foreach ($_POST['cb_fields'] as $cb_fld):
            if (in_array($cb_fld, $fields)):
                $validfield[] = $cb_fld;
            endif;
        endforeach;
        echo "<br/>We now have an array of selected fields that are validated<pre>";
        print_r($validfield);
        echo "</pre>";
    else:
        header("Location: form.php");
        exit;
    endif;
else:
    header("Location:form.php");
    exit;
endif;

so that's the second question done.

the first question i'm not so sure about your meaning. what i did above is set up a table structure by using <tr> (a row marker) and <td></td> (a cell marker). I did this in a loop to populate the table.

the relevant line of code is
Code:
$checkboxes .= "<tr><td><input $checked type=\"checkbox\" name=\"cb_fields[]\" value=\"{$field}\"/></td><td>{$field}</td></tr>";
endforeach;
if you, say, wanted to put this on two lines you could do the following (this is php heredoc syntax but is easier to show you how the html is structured in this form).
Code:
echo <<<EOF
<tr>
 <td>
   <input $checked type="checkbox" name="cb_fields[]" value="$field" />
 </td>
 <td>
  $field
 </td>
</tr>
<tr><!--- Second row starts here -->
 <td>
   &nbsp;
 </td>
 <td>
   Some other variable data goes here
 </td>
</tr>

EOF;
// it is vital that the EOF; is fully abutting the left margin.

hope the second bit is what you were after.
 
Great! I need to put the array values in a string to use in my SQL select statement but I'll figure that out.

What I meant in question1 was I would like to see the database fields (and the check box)displayed across the page so they didn't take up so much room on the screen. I could probably fit 4-6 fields and checkboxes on each line.

You have gone above and beyond. Thanks.
 
right.

i would recommend ditching the table altogether if you're going to go across the screen. that way they *should* wrap gracefully to the window or containing div.

Code:
echo <<<EOF
<span class="wrapper" style="float:left;">
 <span class="cbox" >
   <input $checked type="checkbox" name="cb_fields[]" value="$field" />
 </span>
 <span class="fld" >
  $field
 </span>
</span>
EOF;
// it is vital that the EOF; is fully abutting the left margin.

to use the array in a sql query
Code:
$query = "Select * from TABLE where ";
$searchterm = "some search term";
foreach ($validfields as $validfield):
  $where .= "$validfield like '%$searchterm%' or ";
endforeach;
$query = $query . rtrim($where, "or ");
echo $query;

or if it is just the fields:
Code:
$fields = implode (","$validfields);
$query  = "Select ". rtrim($fields, ",") . " from TABLE";
echo $query;
 
The select works great. The script it is in actually opens an excel spreadsheet. Now my users can dynamically run their own SQL into the spreadsheet which is exciting. Best yet, I now understand what it does.

I was not able to get the check boxes to go across the screen though. I have pasted your 1st script below. Could you make the modifications fo the check boxes go across there? I'm not following the code.

session_start();
$table = "";//enter table name
mysql_connect("","","") or die(mysql_error());
mysql_select_db("") or die(mysql_error());

$result = mysql_query("Show fields from $table") or die (mysql_error());
$checkboxes = "";
while ($row = mysql_fetch_assoc($result)):
$fields[] = $row['Field'];
endwhile;
foreach ($fields as $field):
if(isset($_SESSION['cb_fields'])):
$checked = in_array($field, $_SESSION['cb_fields']) ? "checked" : "";
else:
$checked="";
endif;
$checkboxes .= "<tr><td><input $checked type=\"checkbox\" name=\"cb_fields[]\" value=\"{$field}\"/></td><td>{$field}</td></tr>";
endforeach;
echo "<form action=\"page2.php\" method=\"post\">";
echo "<table>";
echo $checkboxes;
echo "<tr><td></td><td><input type=\"submit\" name=\"submit\" value=\"submit\"></td></tr></table>";
echo "</form>";
 
here you go. change the number of "em" in the style declaration to change the number of checkboxes that go across the page. or leave blank altogether although this will mean each checkbox takes up the minimum space it needs and the list will not be evenly spaced

Code:
<?
session_start();
$table = "tbl_user";//enter table name
mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("adieandco") or die(mysql_error());

$result = mysql_query("Show fields from $table") or die (mysql_error());
$checkboxes = "";
while ($row = mysql_fetch_assoc($result)):
    $fields[] = $row['Field'];
endwhile;
foreach ($fields as $field):
        if(isset($_SESSION['cb_fields'])):
            $checked = in_array($field, $_SESSION['cb_fields']) ? "checked" : "";
        else:
            $checked="";
        endif;
		$checkboxes .= <<<EOF
<span class="wrapper" style="float:left;width:14em;">
 <span class="cbox" >
   <input $checked type="checkbox" name="cb_fields[]" value="$field" />
 </span>
 <span class="fld" >
  $field
 </span>
</span>

EOF;

endforeach;

// it is vital that the EOF; is fully abutting the left margin.endforeach;
echo "<form action=\"page2.php\" method=\"post\">";
//echo "<table>";
echo $checkboxes;
echo <<<EOF
<div style="clear:both;">
<input type="submit" name="submit" value="submit">
</div>

EOF;

echo "</form>";
?>
 
Beautiful. If I'm not pushing my luck could you demonstrate a button to select/deselect all the checkboxes. If I've taken up too much of your time I understand and thanks again for everything.
 
i guess you are asking for javascript. you could probably get a better answer in the js forum. but here is my starter for 10. the whole code is posted for completeness but really the changes are
1. addition of some js
2. giving the form an id
3. addition of another select box and an onchange event call

Code:
<?
session_start();
$table = "tbl_user";//enter table name
mysql_connect("localhost","root","root") or die(mysql_error());
mysql_select_db("adieandco") or die(mysql_error());

$result = mysql_query("Show fields from $table") or die (mysql_error());
$checkboxes = "";
while ($row = mysql_fetch_assoc($result)):
    $fields[] = $row['Field'];
endwhile;
foreach ($fields as $field):
        if(isset($_SESSION['cb_fields'])):
            $checked = in_array($field, $_SESSION['cb_fields']) ? "checked" : "";
        else:
            $checked="";
        endif;
		$checkboxes .= <<<EOF
<span class="wrapper" style="float:left;width:14em;">
 <span class="cbox" >
   <input $checked type="checkbox" name="cb_fields[]" value="$field" />
 </span>
 <span class="fld" >
  $field
 </span>
</span>

EOF;

endforeach;

?>
<script type="text/javascript">
function togglecbs(val) {
	var frm = document.getElementById("frm");
	for (var i = 0; i<frm.elements.length; i++) {
		if ((frm.elements[i].name.indexOf('cb_f') > -1)) {
			frm.elements[i].checked = val;
		}
	}
}
</script>
<?
// it is vital that the EOF; is fully abutting the left margin.endforeach;
echo "<form action=\"page2.php\" method=\"post\" id =\"frm\" >";
//echo "<table>";
echo $checkboxes;
echo <<<EOF
<span class="wrapper" style="float:left;width:14em;">
 <span class="cbox" >
   <input $checked type="checkbox" name="all" value="select all" onclick="togglecbs(this.checked)"/>
 </span>
 <span class="fld" >
  Select/Deselect All
 </span>
</span>
<div style="clear:both;">
<input type="submit" name="submit" value="submit">
</div>

EOF;

echo "</form>";
?>
 
Everything works beautifully. My next step is to allow data selection from my employee file like fulltime/parttime, departments, etc.. You have given me a great platform to work with and I really appreciate your help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top