Simple issue with checkboxes in a SQL form submit - php

So forgive this dumb question. I'm a music teacher, not a programmer.
I am submitting a form. I have possibly checked checkboxes for "spoken languages".
<input type="checkbox" id="speakEnglish" name="speakEnglish" value="yes" />
<input type="checkbox" id="speakGerman" name="speakGerman" value="yes" />
And then on form submit I have
$speakEnglish = $_POST['speakEnglish'];
$speakGerman = $_POST['speakGerman'];
And formulate my SQL query from that. It was submitting and INSERTing fine on my local host, but since uploading to a server I'm getting this when a checkbox is empty...
AN error occurred in the script '/home/berli/public_html/TEST/signup.php' on line 295:
Undefined index: speakGerman
This confuses me .. though I understand whats going on.
But why was my form submitting with empty checkboxes before, and now it throws an error?
What is the normal way to handle this?
Something like..?
if(isset($_POST[checkboxVar]) { $SQLcheckboxVar = $_POST[checkboxVar]} };
I just don't understand why empty checkboxes didn't hang me up on local host, but now they do. I cant think of anything else I could have done to cause that and I certainly wasn't testing for the checkbox variables before... but I have a SQL table full of INSERTed entries.
Is there some kind of difference on how this would work locally vs on a server?

Your servers error reporting must show notices/warnings (not sure specifically which one that is).
You are correct in saying that if(isset($_POST['checkboxVar'])) is all you would need to hide that error if you can't change your php configuration (php.ini). This is what you need on your online server (usually /etc/php.ini):
;Show all errors, except for notices and coding standards warnings
error_reporting = E_ALL & ~E_NOTICE

Your local configuration is probably using the default php settings, which are suppressing any Notices. The production server has a stricter error reporting which lets you know of tiny (most probably not important) problems.
In this case you are trying to access a variable which is not defined, as the browser is NOT sending any data for checkboxes that have not been selected.
As already pointed out above, a simple if(isset($_POST[checkboxVar])) will do the trick to get rid of the notice on per-variable level.
In case you wish to stay a music teacher and not break your head against the wall every time these things pop up it may be easier to simply put the following as the first line of your program:
error_reporting(E_ALL & ~E_NOTICE);

The simplest way to avoid this Notice is to check if your Checkbox has been checked with something like:
if (!isset($_POST['checkboxVar'])) $_POST['checkboxVar'] = 'no';
or
$checkboxVar = isset($_POST['checkboxVar']) ? $_POST['checkboxVar'] : 'no';
The Problem you ran into is, that the browser will not submit anything in the formdata if your checkbox hasn't been checked.

Related

I have an undefined variable, but i don't know why

This is the code i have problem with: http://tutsforweb.blogspot.hu/2012/02/php-installation-script.html
Notice: Undefined variable: pre_error in C:\wamp\www\torolni\install.php
on line 110 Call Stack #TimeMemoryFunctionLocation
10.0022297152{main}( )..\install.php:0 20.0022297824step_2( )..\install.php:13
I have the same problem,as the first commenter, but i don't know how to "close Notice message in your php ini file". What is that? Where can i find it? I use WAMP. Could it be a problem in a "real" server? (Not in localhost)
I can't go to the 3rd step because of the error. Help me please.
They are suggesting to not display PHP notices, but I think it is bad advice because instead of fixing possible code problems that method just hides the message. Fixing the probem would be to initiate the variable:
function step_2(){
$pre_error = '';
//...
}
Let me start off by saying turning off notices to hide your PHP errors is not very good practice at all!
Looking at the error, you cannot echo a non-existent variable. $pre_error is not defined in the case where things work correctly. You can declare this at the start of 'Step 2'.
function step_2(){
$pre_error = '';
if....
It would also be a good idea to update the conditionals in the if statements so that you check the array key exists before testing it's value.
E.g. && $_POST['pre_error'] != '' should change to && (isset($_POST['pre_error']) && $_POST['pre_error'] != '')
Click on your WAMP icon in the taskbar > PHP > php.ini. This will bring you to the text file that sets up your basic PHP behaviors. You can customize those behaviors by following this reference: http://www.php.net/manual/en/function.error-reporting.php
Also, please don't make a PHP installation script. All sorts of security issues will rear their ugly head, especially if you're not using secure FTP over SSL.
To find your php.ini file:
Option 1: Navigate to the corresponding folder on your computer and open the php.ini file with notepad. on mine it is specifically C:\wamp\bin\apache\Apache2.2.17\bin (Your exact location and version of php may be slightly different.
Option 2
Click on the wamp icon in your system tray->PHP->php.ini
In notepad hit ctrl+f and search for display_errors = On. set this to display_errors = Off
Restart your wamp server and the notice should no longer be displayed
This is a very poor fix however as others have mentioned. I would also recommend you turn them back on when you are finished with that tutorials as displaying errors is invaluable when developing.

PHP 5.4: disable warning "Creating default object from empty value"

I want to migrate code from PHP 5.2 to 5.4. This worked fine so far except that all the code I use makes extensive use of just using an object with a member without any initialisation, like:
$MyObject->MyMember = "Hello";
which results in the warning: "Creating default object from empty value"
I know that the solution would be to use:
$MyObject = new stdClass();
$MyObject->MyMember = "Hello";
but it would be A LOT OF WORK to change this in all my code, because I use this many times in different projects. I know, it's not good style, but unfortunately I'm not able to spend the next weeks adding this to all of my code.
I know I could set the php error_reporting to not reporting warnings, but I want to be able to still get other warnings and notices. This warning doesn't seem to be effected by enable or disable E_STRICT at all. So is there a way to just disable this warning?!
Technically you could do this by installing your own error handler for warnings. From inside the handler check the string error message; if it's the one you want to suppress then return true, otherwise return false to let the default error handler do its thing.
However I would still recommend doing the right thing and manually fixing your code wherever this misuse does appear because, if nothing else, it gets you into the correct habit. Unless this is paid work (in which case there usually are concerns that override purity of implementation), consider this as a lesson and do the right thing.
I know I could set the php error_reporting to not reporting warnings, but I want to be able to still get other warnings and notices.
Don't disable the error reporting, leave it at an appropriate level, but disable the display_errors directive:
ini_set('display_errors', 0);
There's no reason to print notices to the screen in production.
Then as Jon said, use a custom error handler if you aren't already, example:
function my_error_handler($error_level, $error_message)
{
// write error message to log file
}
set_error_handler('my_error_handler');
You can pass in the error reporting level to the second param of set_error_handler. This way you can take your time and do the right thing, which is fix the code to stop generating notices.
If you're moving a lot of sites over to 5.4, you can probably have your server admin turn off display_errors in php.ini until you have enough time to fix everything. Better yet, stage everything and fix it before upgrading, but that may not be an option.
you really could use an IDE for php and try to do this:
Search for $MyObject->MyMember = "Hello";
Look for the results and if it brings the right things, try to replace that with:
$MyObject = new stdClass();
$MyObject->MyMember = "Hello";
So maybe the IDE would do the long work for you...
I had the same problem i handle it like bellow in production environment
\error_reporting(\E_ERROR);
I have to say that my application doesn't need/generate errors, it's on a very controlled environment so doing this wouldn't hurt much, but if your application is an error prone one you should have you own error handler and with a proper regex and preg_match ignore the “Creating default object from empty value” warning and log/prompt others at your discretion.

PHP $_POST does not work

I'm working a web application with PHP.
Something wrong is happening that I have never seen before. $_GET is working well, but $_POST does not work exactly. Imagine the form below:
<form action="process.php" method="post">
<input type="text" name="title" />
<input type="submit" value="send" />
</form>
As you see, I've used post for method attribute of the form. In this case, the code below will return error:
<?php
$sentData = $_POST['title'];
echo($sentData);
?>
Error message:
PHP Notice: Undefined index: title in ...
But If I had used $_GET in php scripts and get in the html form codes, everything would work without any error.
There are something more strange.
There are just one form that returns no error while I'm using POST, other forms return error.
When I run this application locally (with Xampp - Apache 2.2) everything works fine without any error, but whenever I run the application an the remote server (IIS 7), I get these errors and problems.
so i would approach this in a couple of different ways:
#Dynamicus is correct, this is only a 'Notice' and not a fatal error (at least you didn't say so in the question), so this may be a difference in your .ini config or with a config definition to suppress errors like so 'error_reporting(0);'
You may want to make a back up of your current running .ini on your local and on the server and copy the working one over to your server and restart Apache and see if that makes a difference.
Why the indexed array (ie $_POST) is producing a warning is somewhat bizarre, but do a "print_r($_POST);" or a "var_dump($_POST);" to see the contents or if anything is off.
if you're using a framework or something that does routing, this could be something to look into.
i hope this helps and there are more settings for error reporting [here] http://php.net/manual/en/function.error-reporting.php
Your input element needs both a name and value property.
Finally I changed the server that my files were located on it. I tried them on another server (same OS), and everything worked fine.
I could not get what was the reason... This was the first time that I was getting this unknown error.
However, thank you all for your suggestions and comments.

PHP: Undefined Index - Yet I defined Them ? :S

Hey all, my first time asking on stackoverflow!
Anyway. So this morning (and most of last night) I have been working on an a project of mine. Its a simple small scale e-commerce site.
Not to bog down with the details of the website, I'll skip straight to it.
Basically, I have my website hosted on a webserver with my own domain. In order to submit the work to my University tutors, I have to transfer the files to their web-server. This can only be accessed when connected to the university network and runs under the path http://jawa/handins/...../
Now in order for the MySQL and PHP to function I have to extract the tables and information from my personal phpmyadmin panel and dump it into the phpmyadmin panel provided on the Uni network. The database is called something alot different but the tables are the same, so a small minute to make sure my mysql_connect functions are pointing to the correct database and everything is working fine. Or at least that is the plan..
For some reason my PHP variables (Which WORK on MY server) are now undefined - How? I havent changed a single piece of code except where the database is and that is it:
//form data
$firstName = strip_tags($_POST['firstName']);
$lastName = strip_tags($_POST['lastName']);
$Email = strip_tags($_POST['Email']);
$userName = strip_tags($_POST['userName']);
$regPass = strip_tags($_POST['regPass']);
$repeatPass = strip_tags($_POST['repeatPass']);
$date = date("Y-m-d");
$permissions = strip_tags($_POST['permissions']);
Everything matches up with the relevant submit fields. There is nothing different with the code I have running on my personal webserver, and the code hosted on the university network. Yet now these variables you see here are not defined. Forgive me for being stupid if it's obvious, but ive been up for 20hrs straight now and I'm getting really agitated with small problems. However I will not vent my frustration out on anyone, it's not your fault!
Essentially, those variables are used for a registration form. Each sumbit field is given the value which is passed on the $_POST[] function. The form is "POSTING" so no problems there. Im just at a loss!
You probably have a different error_reporting level on your own machine, then it is on the other server. Please add error_reporting(E_ALL); to the top of your page, and these will yell at you.
As #Wesley van Opdorp mentioned, your machine must've a different reporting level, if you set it to E_ALL you will see all errors diplayed such as warnings, notices, and fatal errors.
You have to remember, if you're writing code with the error_reporting turned off or it is set to hide warnings or even notices and everything is working fine, if you turn it on, it may affect your code as it will report every single undefined variable and some other warnings as if it's on strict mode. You may have to add additional checks if that's the case like using isset or is_null before using or referring to undefined variables. Just a thought.
#Wesley is probably right about error reporting.
Try this too though. Check if the input has been entered before trying to use it:
$firstName = isset($_POST['firstName'])?strip_tags($_POST['firstName']):null;
Looks rough I know, but looks it can be as easy as this:
$date = date("Y-m-d");
$inputs = array('firstName', 'lastName', 'Email', 'userName', 'regPass', 'repeatPass', 'permissions');
foreach($inputs as $input)
{
$values[$input] = isset($_POST[$input])?$_POST[$input]:null;
//if it was set/used, store it in the variable, if not store null
}
This saves you writing a line for each of the inputs.
So for example $values['firstName'] would have the value of "John" OR null
So when using any of the $values elements check if it's null or use empty() to see if they put in an actual value.

PHP & MySQL - Error Question

I was wondering how can I stop PHP & MySQL errors from displaying to users but still have the errors logged in the server so I know something is wrong.
two ways:
Config your php.ini (turn error off)
Put a # after any action...
Example:
<?php
$a = #mysq_query("a bad query");
echo #$b; // $b donst exist, so thrwos an error but with the # dosnt show anything
?>
I want to point out that there is a good reason to surpress MySQL Errors. If there error gives away too much info about your database set up and schema (by showing the query in the error... joins... etc.) you don't want a live site showing those errors to the public. Of course you would want to log them. So in the interest of security this is a good single reason to not display them on a live site. As I said logging yes. Displaying no.
http://www.php.net/manual/en/errorfunc.configuration.php
Set display_errors to zero and define a log file with error_log in your php.ini or with ini_set or something.

Categories