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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checkbox values being passed 2

Status
Not open for further replies.

jedel

Programmer
Jan 11, 2003
430
AU
Hi all,

I've bee doing some research on checkboxes in PHP and how they work. I've also been playing with them in a project of mine and have found some interesting results.

I found this thread - thread181-27567 and jpadie stated that an unchecked checkbox returns nothing.

I have found that in my project, it does not appear to be the case. Let me describe my settings and what I did to acheive a result.

Firstly my checkboxes are linked to fields that are set to TinyInt meaning they can only accept a 1 or a 0.

Now what I wanted to do was to have the checkboxes checked if there was a 1 in these fields to indicate that the checkbox had in fact been checked previously.

The code below is what I placed into the HTML tag to acheive this
Code:
<?php if ($post['DLApp']==1){ echo "checked='checked'";}?>

What I found was that if I checked a box previously so that the field value was 1 and then unchecked the box the next time around, the field value would then be 0.

I can only conclude that regradless of what the checkbox is set at (checked or unchecked) that it sends something back to the database.

Now my method works fine in this instance, is this method flawed at all?

I'm using an MVC structure in my project, is there any other way of checking the checkboxes when the fields are set at 1?

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
<?php if ($post['DLApp']==1){ echo "checked='checked'";}?>

this is highly unlikely to work in the way that you expect. the post variables are received by php in the $_POST variable. variables in php are case sensitive.

whether checkboxes return values to the server is, I guess, dependent on the browser. I am not aware of any browser that returns unchecked checkboxes, however.

this is the code I would use to test it

Code:
<?php
if (isset($_POST['submit'])){
	$message = getMessage();
} else {
	$message = '';
}
function getMessage(){
	$message = array();
	if (empty($_POST['one'])){
		$message[] = "Checkbox one was not selected";
	} else {
		$message[] = "Checkbox one was selected and the returned value was $_POST[one]";
	}
	if (empty($_POST['two'])){
		$message[] = "Checkbox two was not selected";
	} else {
		$message[] = "Checkbox two was selected and the returned value was $_POST[two]";
	}
	return implode("<br/>\r\n", $message);
}
function getChecked($var){
	if (!empty($_POST[$var])){
		return 'checked="checked"';
	} else {
		return '';
	}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "[URL unfurl="true"]http://www.w3.org/TR/html4/strict.dtd">[/URL]
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
		<title>Check Box testing</title>
		<style type="text/css">
			html, body {padding: 0; margin:0; font-family:Verdana, Geneva, Arial, Helvetica, sans-serif; font-size:small;}
			form {width: 450px;}
			form div {width: 90%;}
			form div#messages {background-color:#FF9966; border: thin solid red; padding: 5px; margin: 2px; font-size:smaller;}
		</style>
	</head>
	<body>
		<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>" >
			<fieldset>
				<legend>Checkbox Test</legend>
			
			<div id="messages">
				<?php echo $message; ?>
			</div>
			<div>
				<input type="checkbox" name="one" value="one" <?php echo getChecked("one"); ?> /> One <br/>
				<input type="checkbox" name="two" value="two" <?php echo getChecked("two"); ?> /> Two <br/>
				<input type="submit" name="submit" value="submit" />
			</div>
			</fieldset>
		</form>
	</body>
</html>

the tests that i have conducted bear out my previous statements.
 
Don't get me wrong,

I expect that you have far more knowledge and experience than I and you've helped me on more than one occasion.

I find it bizzare that we need half a page of code just to get a tick in box!

I'm trying to figure out why this seems to be working for me now with the one line of code.

Could it just be the version of PHPMyAdmin and they've fixed an issue recently? I don't know. All I can write is what this is doing for me.

I'm sure you understand how I have implemented it, maybe you could set something up similar and give it a try?

If you could offer any explanation as to why it's working, I'm all ears.

In the meantime, I'll try your code above.


-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
jpadie,

tried your code and it worked just as suspect your thought it would.

However it also supports my theory that and unchecked box also returns a value. How else would your code know which message to produce?

I too have tested my setup thoroughly....

1) checked box - returns db value to 1
2) unchecked same box - returns db value to 0
3) opened form with line of code, box is checked - returns value of 1 to db
4) opened form with line of code, unchecked same box - returns value of 0 to db.

I'm using firefox three for this. I will try it out in IE and see what happens...

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
My code just tests your browser behaviour. If you just want to make checkboxes sticky use the getchecked function. This can be easily adapted for use with recordset stored values too.

You havent posted any database code so we cannot comment on what happens in that interaction.
 
OK, What sort of code are you look for? I'll post anything you like

PS my code also works in IE...

My database setup is basically a standard table with come VARCHARS and three Boolean fields (TinyInt).

My SQL is nothing out of the ordinary, I have the sprintf function around it, but it is just and update sql just like any other.

I'm using PHP 5 as well.

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
>What sort of code are you look for?
As a side-observer, sure the update sql.
 
OK, Here it is.

Code:
/**
 * Updates the student details 
 */
function update_student($params)
{
   
	$connection = db_connect();
	$query = sprintf("update students
				set
				Surname = '%s',
				FirstName = '%s',
				Email = '%s',
				Street = '%s',
				Suburb = '%s',
				City = '%s',
				PCode = '%s',
				State = '%s',
				Comments = '%s',
				Phone = '%s',
				Login = '%s',
				Pwd = '%s',
				DLApp = '%s',
				DLPros ='%s',
				Registered = '%s',
				UDBy = '%s'
				
				where
				StudentID = '%s'
				",
				mysql_real_escape_string($params['Surname']),
				mysql_real_escape_string($params['FirstName']),
				mysql_real_escape_string($params['Email']),
				mysql_real_escape_string($params['Street']),
				mysql_real_escape_string($params['Suburb']),
				mysql_real_escape_string($params['City']),
				mysql_real_escape_string($params['PCode']),
				mysql_real_escape_string($params['State']),
				mysql_real_escape_string($params['Comments']),
				mysql_real_escape_string($params['Phone']),
				mysql_real_escape_string($params['Login']),
				mysql_real_escape_string($params['Pwd']),
				mysql_real_escape_string($params['DLApp']),
				mysql_real_escape_string($params['DLPros']),
				mysql_real_escape_string($params['Registered']),
				mysql_real_escape_string($params['UDBy']),
				mysql_real_escape_string($params['StudentID'])				
				);

	$result = mysql_query($query);
	
	if(!$result){
		
		return false;
		//echo mysql_error();
		
	}else{
		
		return true;
		//echo mysql_error();
	}
	
}

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
thanks and what is your sql data definition?
 
sql data definition???? Sorry, not entirely up with the lingo...

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
Would the data definition be the field settings in the database?

Here they are:
Surname - VARCHAR(100)
FirstName- VARCHAR(100)
Email - VARCHAR(255)
Street - VARCHAR(50)
Suburb - VARCHAR(50)
City - VARCHAR(50)
PCode - VARCHAR(10)
State - VARCHAR(5)
Comments - TEXT
Phone - VARCHAR(20)
Login - VARCHAR(30)
Pwd _ VARCHAR(30)
DLApp - tinyint(1)
DLPros - tinyint(1)
Registered - tinyint(1)
UDBy - VARCHAR (50)
StudentID int (PRIMARY KEY)

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
no. the data definition would be the create statement you used to create the database.

I am looking to see whether the tinyint fields you have spoken of are set to NOT NULL and given a default value of 0 (although the latter is not necessary).

if so, then this might be the explanation. you would be assigning, say, DLApp to the value of $_POST['DLApp'] which does not exist. PHP would fire off a Notice (which you are probably suppressing) and treat the variable as null. so you would be assigning DLApp to NULL. If you have NOT NULL set on that column and try to assign a value of NULL the mysql (I think) will try to assign the default value instead (you might check in the mysql forum for this as I am not sure - it might be that mysql will fail the query instead). The default value for integer data types is 0 (link)
 
OH, OK,

I'm not sure how to get you that SQL as I built the table manually.

In answer to you question. The three fields in question are set as NULL and have a default as NULL. I agree that the "NULL" in this case will be set to a zero value and that an unchecked box would fire of a value of NULL and that 'NULL' value would be set as a zero because the field is an integer... But at the risk of sounding ignorant, I must ask so what if it does? Have I not achieved the same result.

I have had a look at your getchecked function above and in reality, My line of code is doing pretty much the same thing. It is placing the checked value in the HTML tag if the database field has a value of 1.

The curious thing here is the fact that an unchecked checkbox is in fact firing off a value, albeit a NULL value, and sending that value to the database, thus changing any value that is in the field associated with it.

A question here, how would I be suppressing the notice? do you mean by placing the @ symbol in front of a mysql standard function?(just trying to get up to speed with the lingo)

Hey thanks for looking into this bye the way, I'm finding this thread very educational...

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
I have no idea of what those variables passed are, but the bare-bone update single column update should look like this.
[tt]
$s = "update students set DLApp = ".(isset($_POST['DLApp'])?1:0." where StudentID = '".$_POST['StudentID']."'"; //figurative only
[/tt]
Then elaborate it to all columns etc... with all the safety measures etc...
 
jedel said:
The curious thing here is the fact that an unchecked checkbox is in fact firing off a value, albeit a NULL value, and sending that value to the database, thus changing any value that is in the field associated with it.
[/quote
To be precise, the unchecked checkbox is NOT firing off a value at all. your code receives no input at all for the value. do this to confirm
Code:
echo "<pre>".print_r($_POST, true) . "</pre>";
Because you are not testing whether or not a variable is extant before you use it in your update/insert query. So you are inserting a NULL value in your query.

However, I am surprised that you are getting a zero value out for a field that is set to NULL and that allows NULL values. That is not expected behaviour.

So i guess we need to look further afield for a solution to this anomaly. Some webservers are known to have this precise bug (recognising a tinyint NULL value as a 0). Coldfusion for example. Also some MVC frameworks wrongly interpret NULL as 0. Cake is an example.

Is there anything in your setup that you think could be doing this? are you running queries through an abstraction layer that could be interfering with the results?

As for the concept of "should I worry if it works" (paraphrased), my answer would be "yes". As a coder you need to be in control of your application behaves at each processing point. If it is not behaving as it should you need to work out why and either accept (and learn from) the anomaly or repair it. I would always go with the latter as it makes your code more portable and, given that anomalies often come from frameworks/abstraction layers, they could be fixed in later releases, so breaking your code...
 
Sounds like great advise...

I am well aware of different server "setups" wreaking havoc with a page design. At the moment I'm only using a localhost server on my machine... as far as setup is concerned, whatever the default was. I'm using WAMP server at the moment.

So....my line of code is simply a method of checking a box and not for sending data to a database.

I guess the next step then is how do I incorporate the isset function into the update SQL in my previous post? OR do I have to run the update query and then call up a second update query to update the checkboxes?




-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
Not wanting to completely rely on the experts answers, I have tried to impliment jpadie's and tsuji's code into my update query. Looking at it, it seemed to me to place the isset into this area:

Code:
mysql_real_escape_string($params[isset($_POST['DLApp'])?1:0]),

After trying it out, it did not pass any errors at all, but neither did it give me the value ion the field that I am after. in fact no matter what I do now, i cannot get the value of 1 into the field, checked or unchecked.

This would tell me that the code,if it is working has determined that the checkbox is not isset and therefore will send a 0 to the db.

So I have bee trying to get jpadie's code up to check to see what values are being send by using
Code:
echo "<pre>".print_r($_POST, true) . "</pre>";
but does not produce anything. just this...

Array
(
)

This might tell me that the form did not pass anything at all, so I tried updating one of the text fields and that updated fine, still the Array showed nothing.

The name of the checkbox is "student[DLApp]". This falls in line with the MVC Structure that I'm using.

So how do I get the $_POST data to feed into the SQL?

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
OK friends,

I think I've modified to code to work. I'd appreciate it if you could cast an expert eye over it.

After much trial and error here is the update SQL
Code:
/**
 * Updates the student details 
 */
function update_student($params)
{
 $DLapp = isset($_POST['DLApp'])?1:0 ;
 $DLPros = isset($_POST['DLPros'])?1:0;
 $Reg = isset($_POST['Registered'])?1:0;
   
	$connection = db_connect();
	$query = sprintf("update students
				set
				Surname = '%s',
				FirstName = '%s',
				Email = '%s',
				Street = '%s',
				Suburb = '%s',
				City = '%s',
				PCode = '%s',
				State = '%s',
				Comments = '%s',
				Phone = '%s',
				Login = '%s',
				Pwd = '%s',
				DLApp = $DLapp,
				DLPros = $DLPros,
				Registered = $Reg,
				UDBy = '%s'
				
				where
				StudentID = '%s'
				",
				mysql_real_escape_string($params['Surname']),
				mysql_real_escape_string($params['FirstName']),
				mysql_real_escape_string($params['Email']),
				mysql_real_escape_string($params['Street']),
				mysql_real_escape_string($params['Suburb']),
				mysql_real_escape_string($params['City']),
				mysql_real_escape_string($params['PCode']),
				mysql_real_escape_string($params['State']),
				mysql_real_escape_string($params['Comments']),
				mysql_real_escape_string($params['Phone']),
				mysql_real_escape_string($params['Login']),
				mysql_real_escape_string($params['Pwd']),
				//mysql_real_escape_string($params['DLApp']),
				//mysql_real_escape_string($params['DLPros']),
				//mysql_real_escape_string($params['Registered']),
				mysql_real_escape_string($params['UDBy']),
				mysql_real_escape_string($params['StudentID'])				
				);

	$result = mysql_query($query);
	
	if(!$result){
		
		return false;
		//echo mysql_error();
		
	}else{
		
		return true;
		//echo mysql_error();
	}
	
}

The name of the checkboxes I changed to just "DLApp","DLPros" etc (instead of "student[DLApp]")


Code:
<?php if ($post['DLApp']==1){ echo "checked='checked'";}?>

I still left my line of code (above) in the tag as we have established that all it does is check the box. I could have gone the function way, but I think my line is less code for the same result.

I think that was about it. I'm sure I tried this before and it didn't work. I must have stuffed it up somewhere and when I back tracked an tried again, away it went.

I still can't get jpadies $_POST line to show up. I'm assuming that it will only show on the first page after the form, which i think might be the problem as the controller code redirects after it has called the update SQL.

Anyways, I'd appreciate any input or advice on the code above

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
>I still can't get jpadies $_POST line to show up.
Just a quick note in case you've some clent scripting. My quick look of jpadie's demo has me feel uncomfortable about this line.
> <input type="submit" name="submit" value="submit" />
Can you rename that name to something else, such as "xsubmit" to avoid collision with submit method? see if it helps. Your pages design seem to suggest that the page is posting to itself and any client-side error may result in non-posting at all as one possible outcome.
 
As a quick note again.
[1] The checkbox should be coded with [tt][red]value="1"[/red][/tt] to warrant a check of $_POST['DLApp']=="1" (with quote for the principle).

[2] Also you can add a line in the php like this.
[tt] echo "<div>".var_dump($_POST)."</div>"[/tt]
such as in jpadie's demo before the $message line to see exactly what you get.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top