Forum Moderators: coopster

Message Too Old, No Replies

Notice: Undefined index:

         

Sub_Seven

5:51 pm on Jun 18, 2010 (gmt 0)

10+ Year Member



Hello everybody,

I'm new to PHP and while creating a form I bumped into a problem when inserting data to a MySql db from a checkbox field, I was hoping someone here could help me, I've created the following test code so I could reproduce the error with just whats necessary:

HTML:

<html>
<body>
<form action="insert2.php" name="form" method="post">
<input type="checkbox" name="cb1" value="1" />Check me<br />
<input type="submit" value="Finish">
</form>
</body>
</html>

//

PHP:

<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("test_db", $con);

$sql="INSERT INTO test_table (cb1)
VALUES('{$_POST['cb1']}')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>

//

MySql field values:

Field: cb1
Type: INT
Length/Values1: 1
Default2: None

---

Bottom line is: If I check the checkbox I get the value sent to the db, in this case a "1", if I don't check it, I get the following error: Notice: Undefined index: cb1 in C:\wamp\www\insert2.php on line 11

I have been reading for quite a while and I kinda know I could use isset() to fix the problem but I just don't know how to use isset().

Can anyone please help me out here, thanks everybody :)

Readie

6:38 pm on Jun 18, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to Webmaster World Sub_Seven

Undefined index is an error you get when trying to call a variable that does not exist from an array.

isset is used in an if statement, and will return true if the variable contained exists, or false if it does not.

<?php

$foo = 1;

if(isset($foo)) {
echo 'foo is set';
} else {
echo 'foo is not set';
}

if(isset($bar)) {
echo '<br>bar is set';
} else {
echo '<br>bar is not set';
}

?>

Will output:
foo is set
bar is not set

So, my suggestion on your code is:

if(isset($_POST['cb1'])) {

$sql="INSERT INTO test_table (cb1)
VALUES('{$_POST['cb1']}')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";

}

Sub_Seven

7:11 pm on Jun 18, 2010 (gmt 0)

10+ Year Member



Hello Readie, thank you, I'm glad I joined.

Please excuse my ignorance in the topic, I added the following code:

if(isset($_POST['cb1'])) {

$sql="INSERT INTO test_table (cb1)
VALUES('{$_POST['cb1']}')";

I'm assuming that's all I need since the other part I already had within my code, I am getting the following error:

Parse error: parse error in C:\wamp\www\insert2.php on line 25

This is the way my PHP looks now:

<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("test_db", $con);

$sql="INSERT INTO test_table (cb1)
VALUES('{$_POST['cb1']}')";

if(isset($_POST['cb1'])) {

$sql="INSERT INTO test_table (cb1)
VALUES('{$_POST['cb1']}')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>

Would you be so kind to explain to me what am I doing wrong? Thanks so much for your time.

Sub_Seven

8:07 pm on Jun 18, 2010 (gmt 0)

10+ Year Member



Hey Readie,

I just figured out what you wanted me to do, I can't believe I didn't see it the firs time, it is working great now, thanks so much for the help :)

Readie

8:10 pm on Jun 18, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Glad you got it sorted in the end :)

Please excuse my ignorance in the topic

We were all new at to PHP at one point :)

Sub_Seven

8:46 pm on Jun 18, 2010 (gmt 0)

10+ Year Member



Thanks again,

I might just have one more question, what if you had more than one check box or even more than 100, would I need to make an If statement for every single one or can one If statement take care of all at once?

Readie

8:59 pm on Jun 18, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hmm, depends how you're dealing with it.

If your checkboxes were named like this:

<input name="chk[]"

Then it's a simple matter of looping through them:

[pre]<?php

if(count($_POST)) {
if(isset($_POST['chk']) && $count = count($_POST['chk'])) {
for($i = 0; $i < $count; $i++) {
echo '<br>' . $_POST['chk'][$i];
}
}
}

?>[/pre]

That will output a list of the values of every single ticked checkbox. (name="chk[]" creates an array within the $_POST array)

If you wish to explictly name them however, a solution would be to create an array of the names you used, and loop through that array:

[pre]<?php

$key_names = array(
'foo',
'bar',
'hello',
'world'
);

foreach($key_names as $key) {
if(isset($_POST[$key])) {
echo '<br>' . $_POST[$key];
}
}

?>[/pre]

Sub_Seven

9:27 pm on Jun 18, 2010 (gmt 0)

10+ Year Member



This is really interesting and I can really see my self mastering this sometime in the future, I never wanted anything to do with server side scripting until I started this little project two days ago, I really appreciate your help Readie.

I have more problems when I only check one check box or none at all and hit the submit button, if I check both it adds the records fine.

I'm getting the "Undefined index:" error on line 22. I probably didn't put the code where it was supposed to be, can you take a look at it and tell me where is my flaw? Thanks again for the help.


<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("test_db", $con);

$key_names = array(
'cb1',
'cb2'
);

foreach($key_names as $key) {
if(isset($_POST['$key'])) {
echo '<br>' . $_POST[$key];
}
}

$sql="INSERT INTO test_table (cb1, cb2)
VALUES('{$_POST['cb1']}', '{$_POST['cb2']}')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>

Note: I tried different methods, this is the one that caused less trouble.

Readie

8:46 pm on Jun 19, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



My apologies for just dissapearing like that, but yesterday was a long day, and my bed was calling :)

foreach($key_names as $key) {
if(isset($_POST['$key'])) {
echo '<br>' . $_POST[$key];
}
}

My intention for posting this was merely an example - the idea is you simply saw the logic behind looping through a variable length array.

If you put your SQL string inside the foreach() loop then you can run the same SQL query multiple times (just with different inputs).

Matthew1980

9:28 pm on Jun 19, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi all,

Hope no-one minds me butting in here, but, I strongly suggest that you don't use your root access to your server for testing or release, setup another account, and if needs be just grant the same privileges, it will make good sense in the long run if you do that now, especially if you are on a works network for example.

Again, just thought I should mention that to you - I'm sure as readie will concur ;)

Cheers,
MRb

Sub_Seven

3:07 am on Jun 22, 2010 (gmt 0)

10+ Year Member



@ Readie

That's ok, we all get lost and have things to do. I get that you were trying to make me see it through an example, I guess I'm still not used to see PHP and understand it right away, I have been reading though and trying to get the hang of it, I got the code to work finally and now I'm trying to sanitize it but it is becoming way too complicated, I might be back here with more questions soon, thanks for all the help.

@Matthew1980

Thanks for the advise, I guess right now I'm not concerned because its just my wamp server on my laptop, as I told readie, I'm working on sanitizing the code because I am concerned about security... yet...

Thank you guys for the help, its greatly aprecciated.

Matthew1980

10:32 am on Jun 22, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Sub_Seven,

and now I'm trying to sanitize it but it is becoming way too complicated


Sanitising depends on situation and application of what you want to do, judge what needs to be done each time you code a new project, as not every project uses a mysql back end for example.

WRT root access, even if you are on a laptop - are you on a wireless network? I was of the thought that it didn't matter, until another member gave me a good reason to get into the habit - Root access can be very dangerous.

Cheers,
MRb