I get the error undefined variable err. I've tried isset here but maybe my code is wrong.
if(err ==1)
{
$record = $_POST;
foreach($record as $key=$val) $record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
make sure that you have defined "err" as constant somewhere or use $err instead of err.
There is Two mistrake in your code
1. Forget $ sign which is neccessary in PHP
2. Wrong syntax for foreach loop there will be => sign instead of =
// so right code is
if($err ==1)
{
$record = $_POST;
foreach($record as $key=>$val)
$record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
in php variable have prefix $ symbol or err must be constant,but it is good practice to use constant name as Capital letters
try this code
if( isset($err) && $err == 1 )
{
$record = $_POST;
foreach($record as $key=>$val) $record[$key] = stripslashes($val);
$msg ="Please fill the empty field";
}
EDIT
try to check variable is exist or not using isset()
The reason you are getting undefined is because where you define your err variable you are forgetting to create it as $err.
You need to change every place in your code where you have err variable to $err, not just in the place you have shown in this question. That's why you're still getting undefined after trying the solutions here, because you're only changing to $err in one place.
Related
I am a newbie and trying to implement a simple validation script after reading up, but I can't see how I can have multiple Ifs that will only do an sql insert if all required fields are met. Rather than having the multiple else statements, what is a syntax approach for having all the form validation Ifs together and if one of them fails, then the correct error is shown and the sql is not execute?
if(isset($_POST ['submit'])){
$user_ID = get_current_user_id();
$catErr = $ratingErr = $titleErr = $textErr = "";
if (empty($_POST["category"])) {
$catErr = "Category is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["rating"])) {
$ratingErr = "Rating is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["post_name"])) {
$postErr = "Title is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["text"])) {
$textErr = "Text is required";
} else {
//DO THE INSERT BELOW!
}
//PDO query begins here...
$sql = "INSERT INTO forum(ID,
category,
rating,
post_name,
text
Use one variable for all the error messages and concatenate to it in the branches, so in the end if that variable is still empty string you won't do the insert. (And you don't need any of the empty else blocks that contain nothing but a comment.)
$err = "";
if (empty($_POST["category"])) {
$err .= "<br/>Category is required";
}
if (empty($_POST["rating"])) {
$err .= "<br/>Rating is required";
}
if (empty($_POST["post_name"])) {
$err .= "<br/>Title is required";
}
if (empty($_POST["text"])) {
$err .= "<br/>Text is required";
}
//PDO query begins here...
if($err=='')
{
$sql = "INSERT INTO forum(ID,
category,
rating,
...";
...
}
There are many solutions to your problem. Here are 3 methods of solving your issue.
You could combine all of your if statements like so:
if (empty($_POST['rating']) || empty($_POST'rating']) || ... ) { ... }
and separate them by double pipes.
You could also check the entire array:
if (empty($_POST)) $error = "There was an error!";
You could set a universal error variable and then output it.
A third solution could keep your current syntax but cut down on the amount of lines. You could save lines by doing without brackets. You can create an array and push your errors to the array.
Note: You can use empty() or isset().
// create an array to push errors to
$errors_array = array();
// if a particular field is empty then push the relevant error to the array
if(!isset($_POST['category'])) array_push($errors_array, "Category is required");
if(!isset($_POST['rating'])) array_push($errors_array, "Rating is required");
...
Once you have an array full of errors you can check for them like so:
// if the array is not empty (then there are errors! don't insert!)
if (count($errors_array) > 0) {
// loop through and echo out the errors to the page
for ($i = 0; $i < count($errors_array); $i++) {
echo $errors_array[i];
}
} else {
// success! run your query!
}
You should use javascript to validate the page before it is even processed into a post. This script will run client-side when they hit submit and catch errors before they even leave the page.
Here's a tutorial on how to do something like that: tutorial
Each field can have its own validation parameters and methods, and it will also make the page's code look a lot nicer.
I got it to go with this approach after showdev got me thinking that way. It's not very elegant perhaps, but does the trick, although all the user is taken to a blank page if there are errors and it simple says: Missing category (or whatever). Wondering if I can echo a link or something back to the page with the form from there so the user has an option like "go back and resubmit". Otherwise I will have to handle and display the errors alongside the form which will require a different approach altogether...
if(isset($_POST ['submit'])){
$errors = false;
if(empty($_POST['category'])) {
echo 'Missing category.<br>';
$errors = true;
}
if(empty($_POST['rating'])) {
echo 'Missing rating.<br>';
$errors = true;
}
if(empty($_POST['post_name'])) {
echo 'Missing title.<br>';
$errors = true;
}
if(empty($_POST['text'])) {
echo 'Missing text.<br>';
$errors = true;
}
if($errors) {
exit;
}
// THEN ADD CODE HERE. But how display form again if user makes errors and sees nothing but error message on page if they miss something (which is how it works now)
Generally, if you find yourself repeatedly writing very similar statements, using some sort of loop is probably a better way to go about it. I think what you said about "handling and displaying the errors alongside the form" is really what you need to do if you want the process to be user-friendly. If you put your validation script at the top of the file that has your form in it, then you can just have the form submit to itself (action=""). If the submission is successful, you can redirect the user elsewhere, and if not, they will see the form again, with error messages in useful places.
if (isset($_POST['submit'])) {
// define your required fields and create an array to hold errors
$required = array('category', 'rating', 'post_name', 'text');
$errors = array();
// loop over the required fields array and verify their non-emptiness
foreach ($required as $field) {
// Use empty rather than isset here. isset only checks that the
// variable exists and is not null, so blank entries can pass.
if (empty($_POST[$field])) {
$errors[$field] = "$field is required";
}
}
if (empty($errors)) {
// insert the record; redirect to a success page (or wherever)
}
}
// Display the form, showing errors from the $errors array next to the
// corresponding inputs
I have a problem with the understanding of variable scopes.
I've got a huge .php file with many $_POST validations (I know that isn't not good practise). Anyways I want a little html-part above all the code which outputs an error message. This message I want to change in every $_POST validation function.
Example:
if($ERR) {
echo '<div class="error-message">'.$ERR.'</div>';
}
Now my functions are following in the same file.
if(isset($_POST['test']) {
$ERR = 'Error!';
}
if(isset($_POST['test2'] {
$ERR = 'Error 2!';
}
But that doesn't work. I think there's a huge missunderstanding and i'm ashamed.
Can you help me?
I didnt catch your question but maybe this is your answer:
<body>
<p id="error_message">
<?php if(isset($ERR)){echo $ERR;} ?>
</p>
</body>
and I suggest you to learn how to work with sessions.
and you should know that $_Post will be empty on each refresh or F5
You can do put the errors in array make them dynamic.
<?php
$error = array();
if (!isset($_POST["test"]) || empty($_POST["test"])) {
$error['test'] = "test Field is required";
} else if (!isset($_POST["test1"]) || empty($_POST["test1"])) {
$error['test1'] = "test Field is required";
}else{
//do something else
}
?>
You can also use switch statement instead of elseif which is neater.
I don't know where I am going wrong in else if logic...
I want to validate this signup script in 3 steps:
1st: check if any field is empty, in which case include errorreg.php and register.php.
2nd: If email already exists include register.php.
3rd: If all goes well insert data to the database.
<?php
$address =$_POST["add"];
$password =$_POST["pw"];
$firstname =$_POST["fname"];
$lastname =$_POST["lname"];
$email =$_POST["email"];
$contact =$_POST["cno"];
$con=mysql_connect("localhost","root","");
mysql_select_db("bookstore");
$q2=mysql_query("select * from customer where email='$email'");
$b=mysql_fetch_row($q2);
$em=$b[0];
if($password != $_POST['pwr'] || !$_POST['email'] || !$_POST["cno"] || !$_POST["fname"] || !$_POST["lname"] || !$_POST["add"])
{
include 'errorreg.php';
include 'register.php';
}
else if($em==$email)
{
echo 'email already present try another';
include 'register.php';
}
else
{
$con=mysql_connect("localhost","root","");
mysql_select_db("bookstore");
$q1=mysql_query("insert into customer values('$email','$password','$firstname','$lastname','$address',$contact)");
echo 'query completed';
$q2=mysql_query("select * from customer where email='$email'");
$a=mysql_fetch_row($q2);
print "<table border =2px solid red> <tr><th>id </th></tr>";
print "<td>$a[0]</td>";
print "</table>";
include 'sucessreg.php';
echo " <a href='newhome.php'>goto homepage</a>";
}
?>
There's a lot to correct here, but to your specific concern, that the "loop" doesn't go on to the second and third "steps", that's because you're thinking about this wrong. In an if/else if/else code block, only one of the blocks is executed at a time, the others are not. For instance, if a user submitted a number, we could tell them it was even or odd with the following:
if($_GET['number'] % 2 == 0){
echo "That's even!";
} else {
echo "That's odd!";
}
You are attempting to do one check, then another, then a third. In this case, you want to nest your conditionals (if statements) rather than have them come one after another, like so:
if(/* first, basic sanity check*/) {
if(/* second, more complex check */) {
if(/* final check */) {
// Database update
} else {
// Failed final check
}
} else {
// Failed second check
}
} else {
// Failed basic check
}
Some other comments on your code:
Pay attention to formatting - laying out your code in consistent and visually clear patterns will help make it easier to see when you make a mistake.
Use isset($_POST['variable']) before using $_POST['variable'], otherwise you'll get errors. One idea is to use lines like: $address = isset($_POST['address']) ? $_POST["add"] : ''; - if you don't know that notation, it lets you set $address to either the value from the $_POST array or '' if it's not set.
Use the variables you created, like $email and $contact, rather than re-calling the $_POST variables - they're clearer, shorter variable names.
Use the better MySQLi library, rather than the MySQL library.
Create one connection ($con = ...) to your database at the beginning of your script, and don't create a second one later on, like you do here.
Explicitly specify which connection your queries are running against - you say $q2=mysql_query("SELECT ...") but you should also pass the connection you've constructed,
$q2=mysql_query("SELECT ...",$con).
First of all you want to check if the property isset in your $_POST object:
if(isset($_POST["name"])
second you want to check if the value set is empty
if(isset($_POST["name"] && !empty($_POST["name"]))
now you just have to scale it up to check all your properties it would be handy to move it into a function like this
function ispostset($post_var)
{
if (isset($_POST[$post_var]))
{
if ($_POST[$post_var] != '')
{
return true;
}
else
return false;
}
else
return false;
}
I have this code:
print_r(array_keys($variables));
if (array_key_exists('form', $variables)) {
print "YES!";
}
$imgs = $variables['form']['field_images'];
It's a part of the code that I use to theme a form page in Drupal. YES is printed out, however, drupal reports undefined index for that. Thanks for your generous help
$variables['form'] does exist, but $variables['form']['field_images] probably not. That's why you get the notice about undefined index.
So you should make sure that the subkey also exists before you are calling it.
as an example implemenation of Ikke`s answer:
if ( !array_key_exists('form', $variables) ) {
echo 'missing parameter form';
}
else if ( !array_key_exists('field_images', $variables['form']) ) {
echo 'missing parameter field_images';
}
else {
$imgs = $variables['form']['field_images'];
}
Try this:-
PHP throws the notice. You can add an isset() or !empty() check to avoid the error, like such:
if(isset($variables)) ) && !empty($variables)) ))
{
if (array_key_exists('form', $variables)) {
print "YES!";
}
$imgs = $variables['form']['field_images'];
}
I am using adldap http://adldap.sourceforge.net/
And I am passing the session from page to page, and checking to make sure the username within the session is a member of a certain member group, for this example, it is the STAFF group.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once('/web/ee_web/include/adLDAP.php');
$adldap = new adLDAP();
session_start();
$group = "STAFF";
//$authUser = $adldap->authenticate($username, $password);
$result=$adldap->user_groups($_SESSION['user_session']);
foreach($result as $key=>$value) {
switch($value) {
case $group:
print '<h3>'.$group.'</h3>';
break;
default:
print '<h3>Did not find specific value: '.$value.'</h3>';
}
if($value == $group) { print 'for loop broke'; break; }
}
?>
It gives me the error: Warning: Invalid argument supplied for foreach() on line 15, which is this line of code: foreach($result as $key=>$value) {
When I uncomment the code $authUser = $adldap->authenticate($username, $password); and enter in the appropriate username and password, it works fine, but I shouldn't have to, since the session is valid, I just want to see if the username stored within the valid_session is apart of the STAFF group.
Why would it be giving me that problem?
According to this source file, user_groups() will, return false if the user name was empty (and in some other cases too, check the source). I bet your $_SESSION["user_session"] is empty, and $result is then false. You can't run foreach on a non-array which is why you get the warning.
You will need to find out why your session variable is empty, and/or check whether $result is an array because doing a foreach on it:
if (is_array($result))
foreach ($result....