Using HTML checkboxes with PHP

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
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Using HTML checkboxes with PHP

Post by jayshields »

Hi guys,

My first time on here - be gentle!

I'm trying to code a Newsletter system, but I cannot grasp how to tell PHP if a checkbox has been selected or not.

Here is my code (you only need to look at the recipients bit):

Code: Select all

<?php 

//Include the HTML header 
include ('includes/header.html'); 

//Connect to MySQL 
require_once ('config.php'); 

//**HOME*** 
if ($_GET['page'] == "") { 

//Print the content 
echo '<b><u>Welcome to PHPJayMail, by Jay-Designs.co.uk</b></u><br><br>'; 
echo 'Please select a page from the list below:<br>'; 
echo '<a href="index.php?page=recipients">Edit/View Recipients</a><br>'; 
echo '<a href="index.php?page=sendmail">Send Mail</a>'; 

} 
//********* 

//***RECIPIENTS*** 
if ($_GET['page'] == "recipients") { 

//If records need to be deleted... 
if ($_POST['delete']) { 
$query = "SELECT email FROM " . TBL_NAME; 
$result = @mysql_query ($query); 

$x = 1; 

while ($row = mysql_fetch_array ($result, MYSQL_NUM)) { 
if ($x == "selected") { 
$query = "DELETE FROM " . TBL_NAME . " WHERE email = '" . $row['0'] . "'"; 
$result = @mysql_query ($query); 

if ($result) { 
header ("Location: http://" . URL . "/index.php?page=recipients"); 
$message = "You successfully deleted the record(s)!<br>"; 
} else { 
header ("Location: http://" . URL . "/index.php?page=recipients"); 
$message = "Sorry, but there has been a technical difficulty.<br>"; 
} 
} 
$x++; 
} 
} 

//Print the title 
echo '<b><u>', $_GET['page'], '</u></b>'; 

//Print the message if there is one 
if (isset($message)) { 
echo $message; 
} 

//Fetch the mailing list 
$query = "SELECT * FROM " . TBL_NAME; 
$result = @mysql_query ($query); 

//Initialise the $first and $x variables 
$first = 1; 
$x = 1; 

//Print the mailing list 
while ($row = mysql_fetch_array ($result, MYSQL_NUM)) { 
if ($first) { 
echo '<form action="index.php?page=recipients" method="post"><table border="1"><tr><td><b>Email</b></td><td><b>Name</b></td><td><b>Approved?</b></td><td><b>Select</b></td></tr>'; 
} 
echo '<tr><td>' . $row['0'] . '</td><td>' . $row['1'] . '</td><td align="center">' . $row['2'] . '</td><td align="center"><input type="checkbox" name="box" value="' . $row['0'] . '"></tr>'; 
$first = 0; 
$x++; 
} 
echo '<tr><td colspan="4" align="center">With selected: <input type="submit" name="delete" value="Delete"> <input type="submit" name="approve" value="Approve"> <input type="submit" name="unapprove" value="Unapprove"></td></tr></table>'; 

} 
//********* 

//Close the MySQL connection 
mysql_close(); 

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

?>

Ok. That's it. I just want PHP to know which checkboxes were selected when the page is submitted (or one of the 3 buttons are used (at the moment I'm working on the Delete button)). I can see that $x would never equal selected, but the thing that troubles me is how to create a dynamic checkbox name/value/w/e and then refer to it when its been submitted without it looking at the true or fake value (I hope you can see where I'm coming from).

I don't get any errors or anything the page just acts like it's refreshing.

Any ideas would be great.

Thanks in Advance.


feyd | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

If you have 5 checkboxes - with name attributes - chk1, chk2, chk3, chk4, chk5 and you select only chk2 and chk5 - only these 2 would be sent as POST variables.
$_POST['chk2'] and $_POST['chk5'] would be set while the others dont exist.
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

yeah i understand that, but I am inserting all my records into a html table usiong a while loop. if you take a look at the code it dumps a mysql table into the html table and adds a check box onto the end of every row. so i cannot name these individually.

also, even if i made the dynamic check box names using php i wouldnt be able to refer to them when the page has been submitted and check if they were set because they would always be set, because i would have to make a string to refer to the full check box name. atleast i dont think i would be able to do it that way! i tried something similar but explaining it just confuses me.

thanks for your help anyway.

any other ideas?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

you actually can name them dynamically, yet maintain the selection list easily in php. A quick example:

Code: Select all

<?php ?>
<html>
<body>
<?php

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
  echo '<pre>'.htmlentities(var_export($_POST['chex'],true)).'</pre>';
}

echo '<form method="post">';

for($i = 0; $i < 15; $i++)
{
  echo '<input type="checkbox" name="chex['.$i.']" id="chex_'.$i.'" value="'.$i.'"'.(mt_rand() % 2 ? ' selected="selected"' : '').' /><label for="chex_'.$i.'">checkbox '.($i + 1).'</label><br />';
}

echo '</form>';

?>
</body>
</html>

jayshields, read your pm's
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

I can't quite grasp what your trying to get acorss to me here.

Do you mean that all I would have to do is set the checkbox name to "something[uniquenumber]"?

In that case, how would I refer to it if I was to put:

Code: Select all

if (isset($_POST['variable']))
what variable name would i call up?

by the way, i read my pms and changed my sig.

sorry about that.

thanks for any help.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it'd be accessed via $_POST['something'] to use your example. The end result is an array, where each key is what you set in the brackets (if nothing, they are a sequential list of the selected ones)
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

ok after spending a couple more hours on this i am seriously considering throwing my pc out of the window.

Code: Select all

if ($_GET['page'] == "recipients") {

	//If records need to be deleted...
	if ($_POST['delete']) {
		$query = "SELECT * FROM " . TBL_NAME;
		$result = @mysql_query ($query);
		
		$x = 0;

		while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {
			if (isset($_POST['box'][$x])) {
				$query = "DELETE FROM " . TBL_NAME . " WHERE user_id = " . $x+1;
				//$result = @mysql_query ($query);
			}
			$x++;
		}
	
		//if ($result) {
		//	header ("Location: http://" . URL . "/index.php?page=recipients");
		//	$message = "<font color=\"green\">You successfully deleted the record(s)!</font><br>";
		//} else {
		//	header ("Location: http://" . URL . "/index.php?page=recipients");
		//	$message = "<font color=\"red\">Sorry, but there has been a technical difficulty.</font><br>";
		//}

	} //End of the 'delete' conditional

	//Print the title
	echo '<b><u>Recipients</u></b>';

	//Print the message if there is one
	if (isset($message)) {
		echo '<br><br>' . $message . '<br>';
	}
	
	echo '<br><br>query is: ' . $query . '<br><br>';

	//Fetch the mailing list
	$query = "SELECT * FROM " . TBL_NAME;
	$result = @mysql_query ($query);

	//Initialise the $first and $z variables
	$first = 1;
	$z = 0;

	//Print the mailing list
	while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {
		if ($first) {
			echo '<form action="index.php?page=recipients" method="post">';
			echo '<table border="1">';
			echo '<tr>';
			echo '<td><b>Email</b></td><td><b>Name</b></td><td><b>Approved?</b></td><td><b>Select</b></td>';
			echo '</tr>';
		}
		echo '<tr>';
		echo '<td>' . $row['1'] . '</td>';
		echo '<td>' . $row['2'] . '</td>';
		echo '<td align="center">' . $row['3'] . '</td>';
		echo '<td align="center"><input type="checkbox" name="box[' . $z . ']">';
		echo '</tr>';
		$first = 0;
		$z++;
	}
	echo '<tr>';
	echo '<td colspan="4" align="center">With selected: <input type="submit" name="delete" value="Delete"> <input type="submit" name="approve" value="Approve"> <input type="submit" name="unapprove" value="Unapprove"></td>';
	echo '</tr>';
	echo '</form>';
	echo '</table>';

}
This is just the section of code I am working on. Before you ask, I am connected to MySQL, but above this snippet. On my page, $query is echoed out as being "1". How can it possibly be just "1"?!?!?!?! A minute ago it was very nearly working, I could get the box array to output on for however many boxes were checked.

Does anyone know where I am going wrong?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

a delete query returns true/non-zero for success, false/zero for failure.
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

Post by jayshields »

yeah i know that, but before i even think about trying to execute my query i want it to atleast show up so i know i am executing the right thing. why it shows "1" is beyond me.
User avatar
jayshields
DevNet Resident
Posts: 1912
Joined: Mon Aug 22, 2005 12:11 pm
Location: Leeds/Manchester, England

SOLVED!

Post by jayshields »

OMG I'VE DONE IT!!! WAAHHOOO!!

Persistance does indeed pay off eventually.

Here is my submitted page code:

Code: Select all

//If records need to be changed...
	if ($_POST['delete'] || $_POST['approve'] || $_POST['unapprove']) {
		
		if (isset($_POST['box'])) { //If a checkbox has been ticked...
			
			//Make and set the values of the boxArray
			$boxArray = array();
			$boxArray = $_POST['box'];

			foreach ($boxArray as $x) { //For each value in the boxArray
				
				if ($_POST['delete']) { //If the user wants to delete a record...
					$query = "DELETE FROM " . TBL_NAME . " WHERE user_id = " . $x; //Make a query to delete the record
					$result = @mysql_query ($query); //Execute the query
					$message = "<font color=\"green\">You successfully deleted the record(s)!</font><br>"; //Set the message
				}

				if ($_POST['approve']) { //If the user wants to approve a record...
					$query = "UPDATE " . TBL_NAME . " SET approved = 'Y' WHERE user_id = " . $x; //Make a query to approve a record
					$result = @mysql_query ($query); //Execute the query
					$message = "<font color=\"green\">You successfully approved the record(s)!</font><br>"; //Set the message
				}

				if ($_POST['unapprove']) { //If the user wants to unapprove a record...
					$query = "UPDATE " . TBL_NAME . " SET approved = 'N' WHERE user_id = " . $x; //Make a query to unapprove a record
					$result = @mysql_query ($query); //Execute the query
					$message = "<font color=\"green\">You successfully unapproved the record(s)!</font><br>"; //Set the message
				}

			}

		}

	} //End of the change records conditional
and here is my html table code:

Code: Select all

//Fetch the mailing list
	$query = "SELECT * FROM " . TBL_NAME . " ORDER BY name ASC";
	$result = @mysql_query ($query);

	//Initialise the $first and $z variables
	$first = 1;
	
	if ($row = mysql_fetch_array ($result)) { //If no records are in the table make an empty one...
		echo "";
	} else {
		echo '<form action="index.php?page=recipients" method="post">';
		echo '<table border="1">';
		echo '<tr>';
		echo '<td><b>Name</b></td><td><b>Email</b></td><td><b>Approved?</b></td><td><b>Select</b></td>';
		echo '</tr>';
		echo '<tr>';
		echo '<td colspan="4" align="center">';
		echo 'There are no records to display!';
		echo '</td>';
		echo '</tr>';
	}


	//Print the mailing list
	while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {
		if ($first) {
			echo '<form action="index.php?page=recipients" method="post">';
			echo '<table border="1">';
			echo '<tr>';
			echo '<td><b>Name</b></td><td><b>Email</b></td><td><b>Approved?</b></td><td><b>Select</b></td>';
			echo '</tr>';
		}
		echo '<tr';
		if ($row['3'] == "N") {
			echo ' bgcolor="#FF9999"';
		} elseif ($row['3'] == "Y") {
			echo ' bgcolor="#99FF99"';
		}
		echo '>';
		echo '<td>' . $row['2'] . '</td>';
		echo '<td>' . $row['1'] . '</td>';
		echo '<td align="center">' . $row['3'] . '</td>';
		echo '<td align="center"><input type="checkbox" name="box[' . $row[0] . ']" value="' . $row[0] . '">';
		echo '</tr>';
		$first = 0;
	}
	echo '<tr>';
	echo '<td colspan="4" align="center">With selected: <input type="submit" name="delete" value="Delete"> <input type="submit" name="approve" value="Approve"> <input type="submit" name="unapprove" value="Unapprove"></td>';
	echo '</tr>';
	echo '</form>';
	echo '</table>';
I'm so chuffed now!

Thanks alot for the help guys :) I know where to come in future!
Post Reply