Why does my button trigger PHP when I'm pressing the button? - php

I have created a PHP script that allows users on my site to sign up for our newsletter by entering their email and pressing the submit button. Then, it will give the user a notification to say that they have successfully signed up for our newsletter, and I will get an email. However, when you load the page (https://papaya-os.000webhostapp.com/) it sends me the email saying that somebody signed up, but the submit button was never pressed, and it doesn't show a success notification. On top of that, when you try to use the form correctly it doesn't work. Here is my PHP:
if($_POST["submit"]) {
if(!$_POST["email"]) {
$error = 'Please Enter Your Email';
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were error(s) in submitting the form: ' .$error. '</strong></div>';
}
} else {
if(mail("colin.vrugteman#hotmail.com", "Newsletter Sign Up", "Email: ".$_POST['email'])) {
$result='<div class="alert alert-success">Thank You. You have been signed up for our newsletter!</div>';
}
}
?>
I tried running the PHP on the top, and then the bottom of my HTML code, but neither worked. Any help is appreciated. Thanks!

you have mistake in parenthesis
if($_POST["submit"]) {
if(!$_POST["email"]) {
$error = 'Please Enter Your Email';
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were error(s) in submitting the form: ' .$error. '</strong></div>';
} else {
if(mail("colin.vrugteman#hotmail.com", "Newsletter Sign Up", "Email: ".$_POST['email'])) {
$result='<div class="alert alert-success">Thank You. You have been signed up for our newsletter!</div>';
}
}
}

<?
//Here you should be checking if submit is set, or `empty()` is my preferred function. You could also use `isset()` but you would want to negate that, so it would be `!isset()`.
if(empty($_POST["submit"])) {
//If email is empty, set $error
if(empty($_POST["email"])) {
$error = 'Please Enter Your Email';
}
//if $error is not empty, set $result
if (!empty($error)) {
$result = '<div class="alert alert-danger"><strong>There were error(s) in submitting the form: ' . $error . '</strong></div>';
}
//if $_POST["submit"] IS set, send email.
} else {
//if $_POST['submit'] is NOT empty, and IS set, send email.
if(isset($_POST['submit'])) {
if (mail("colin.vrugteman#hotmail.com", "Newsletter Sign Up", "Email: " . $_POST['email'])) {
$result = '<div class="alert alert-success">Thank You. You have been signed up for our newsletter!</div>';
}
}
}
?>
Try this code, and I added comments to explain what was happening.
I personally would have wrote it to be more dynamic with the error code.
Here is how I would have personally wrote the code. I'm not claiming this is better or worse, just how I would have done it. :)
<?php
//if submit is empty there was an issue
if (empty($_POST['submit'])) {
//create an empty array to store errors
$errors = array();
//loop through each _POST element to see what you are missing. If any value is empty or not set, it will be added to the errors.
foreach ($_POST as $key => $value) {
//skip key submit because we don't want that to appear in the errors, you could also add more you want to skip here.
if ($key == "submit")
continue;
//If value is empty/not set, add it to the error array.
if (empty($value)) {
array_push($errors, "Please provide " . ((in_array($key[0], $vocals)) ? "an" : "a") . " {$key}");
}
}
//check if $errors has any contents
if (!empty($errors)) {
//create $results filled with the dynamic errors from above. If there is only 1 error, properly format the sentence.
$result = '<div class="alert alert-danger"><strong>There '.((count($errors)==1)? "was an error" : "were errors" ).' while submitting the form: ';
foreach ($errors as $key => $value) {
$result .= "{$value}";
if ($key != count($errors) - 1) {
$result .= ", ";
}
}
$result .= '</strong></div>';
}
} else {
//if if $_POST['submit'] is not empty and IS set, send email.
if(isset($_POST['submit'])) {
$to = "test#email.com";
$subject = "Newsletter Sign Up";
$message = "Email: {$_POST['email]}";
if (mail($to, $subject, $message)) {
$result = '<div class="alert alert-success">Thank You. You have been signed up for our newsletter!</div>';
}
}
}
?>

You're structure is wrong so it's always hitting that block. You have the closing bracket for your if in the wrong place. Try this.
<?php
if($_POST["submit"]) {
if(!$_POST["email"]) {
$error = 'Please Enter Your Email';
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were error(s) in submitting the form: ' .$error. '</strong></div>';
} else {
if(mail("colin.vrugteman#hotmail.com", "Newsletter Sign Up", "Email: ".$_POST['email'])) {
$result='<div class="alert alert-success">Thank You. You have been signed up for our newsletter!</div>';
}
}
}
?>

Related

Stop PHP Execution But Display HTML

In a Profile page of the User, I want to validate his input with PHP after submission and display errors on the same page before updating in the database.
For this, I'm doing something like:
<div>
<?php
if (isset($_POST["submitted"])) {
if (!isValidEmail($_POST["email"])) {
echo "<p>Please enter a valid email address.</p>";
return; // or exit;
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
echo "<p>Please enter a valid phone number.</p>";
return; // or exit;
}
...
if (updateUser($id, $email, $phoneNumber, $name)) {
echo("<meta http-equiv='refresh' content='0'>");
} else {
echo "<p>An error occurred! Could not update your profile information!</p>";
}
}
?>
</div>
<my-footer></my-footer>
So when an error occurs upon PHP validation, the footer doesn't appear. So I understood that with return or exit the page will stop rendering at that command.
What can I do to solve this issue?
I want it to stop execution of the PHP script but display the rest of the HTML page.
You could put your validation logic inside a function at the top of your page, and change all your echo to return.
function validate() {
if (isset($_POST["submitted"])) {
if (!isValidEmail($_POST["email"])) {
return "<p>Please enter a valid email address.</p>";
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
return "<p>Please enter a valid phone number.</p>";
}
//...
if (updateUser($id, $email, $phoneNumber, $name)) {
return "<meta http-equiv='refresh' content='0'>";
} else {
return "<p>An error occurred! Could not update your profile information!</p>";
}
}
}
Then simply echo the string returned from the function above the footer.
<div>
<?php echo validate(); ?>
</div>
<my-footer></my-footer>
Note that the above will work because $_POST is a superglobal. However, you may consider changing your function to pass email, phoneNumber, name and id as parameters instead.
Change your flow up a little bit...
if (isset($_POST["submitted"])) {
$has_errors = FALSE;
$err_msg = '';
if (!isValidEmail($_POST["email"])) {
$err_msg .= "<p>Please enter a valid email address.</p>";
$has_errors = TRUE;
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
$err_msg .= "<p>Please enter a valid phone number.</p>";
$has_errors = TRUE;
}
if ( $has_errors ) {
echo "<p>Please Correct the following and resubmit...</p>" . $err_msg;
} else {
if (updateUser($id, $email, $phoneNumber, $name)) {
echo("<meta http-equiv='refresh' content='0'>");
} else {
echo "<p>An error occurred! Could not update your profile information!</p>";
}
}
}
Many times you will see PHP frameworks that can handle this for you.
Here's a good website to compare a few: http://phpframeworks.com/
But what you can do is put your footer (and / or the rest of your code) into a function that holds the rest of your code for you, and you can call it later or whenever you need to so you can still end code execution gracefully.
<div>
<?php
function footer() {
$string = "</div>";
$string .= "<my-footer></my-footer>";
return $string;
}
if (isset($_POST["submitted"])) {
if (!isValidEmail($_POST["email"])) {
echo "<p>Please enter a valid email address.</p>";
die(footer()); // Displays footer
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
echo "<p>Please enter a valid phone number.</p>";
die(footer()); // Displays footer
}
...
if (updateUser($id, $email, $phoneNumber, $name)) {
echo("<meta http-equiv='refresh' content='0'>");
} else {
die("<p>An error occurred! Could not update your profile information!</p>" . footer()); // kills the page execution, but still returns the foot of the page.
}
}
echo footer();
?>

table just inserts one row. there is an auto increment id

This is my registration code.
Once I enter the fields in the form it shows me registration successful but adds blank data in my database table. It adds number 0 in my mobileno column.
Please help me here asap
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['mobileno'])) {//if no name has been supplied
$error[] = 'Please Enter a Mobile Number ';//add to array "error"
} else {
$name = $_POST['mobileno'];//else assign it a variable
}
if (empty($_POST['fname'])) {//if no name has been supplied
$error[] = 'Please Enter a First name ';//add to array "error"
} else {
$name = $_POST['fname'];//else assign it a variable
}
if (empty($_POST['lname'])) {//if no name has been supplied
$error[] = 'Please Enter a Last name ';//add to array "error"
} else {
$name = $_POST['lname'];//else assign it a variable
}
if (empty($_POST['email'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA- Z0-9\._-]+)+$/", $_POST['email'])) {
//regular expression for email validation
$Email = $_POST['email'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['passwd1'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['passwd1'];
}
if (empty($_POST['passwd2'])) {
$error[] = 'Please Verify Your Password ';
} else {
$Password = $_POST['passwd2'];
}
if (empty($error)) //send to Database if there's no error '
{ //If everything's OK...
// Make sure the mobile no is available:
$query_verify_mobileno = "SELECT * FROM userdtls WHERE mobileno = '$mobileno'";
$result_verify_mobileno = mysqli_query($dbc, $query_verify_mobileno);
if (!$result_verify_mobileno)
{//if the Query Failed ,similar to if($result_verify_mobileno==false)
echo ' Database Error Occured ';
}
if (mysqli_num_rows($result_verify_mobileno) == 0) { // IF no previous user is using this number .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO userdtls (`mobileno`, `pass`, `fname`, `lname`, `email`, `activation`) VALUES ( '$mobileno', '$passwd1', '$fname', '$lname', '$email', '$activation')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send the email:
$message = " To activate your account, please click on this link:\n\n";
$message .= WEBSITE_URL . '/activate.php?email=' . urlencode($Email) . "&key=$activation";
mail($Email, 'Registration Confirmation', $message, 'From: rahul19dj#gmail.com');
// Flush the buffered output.
// Finish the page:
echo '<div class="success">Thank you for registering! A confirmation email has been sent to '.$email.' Please click on the Activation Link to Activate your account </div>';
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
}
} else { // The mobile number is not available.
echo '<div class="errormsgbox" >That mobile number has already been registered.</div>';
}
} else {//If the "error" array contains error msg , display them
echo '<div class="errormsgbox"> <ol>';
foreach ($error as $key => $values) {
echo ' <li>'.$values.'</li>';
}
echo '</ol></div>';
}
mysqli_close($dbc);//Close the DB Connection
} // End of the main Submit conditional.
You're assigning all of your variables, except $email to $name overwriting each one in succession. This is definitely going to cause strange results which are dependant on the data types of each column in your dataase. If mobileno is set to be an int has a default value of 0 a string or empty value will result in you seeing 0 in your dataase.

if !isset multiple OR conditions

I cannot get this to work for the life of me, it is PHP.
<?php
if (!isset($_POST['ign']) || ($_POST['email'])) {
echo "Please enter all of the values!";
}
else {
echo "Thanks, " . $_POST['ign'] . ", you will recieve an email when the site is complete!";
}
?>
I've also tried using !isset twice.
isset() accepts more than just oneparameter, so just pass as many variables as you need to check:
<?php
if (!isset($_POST['ign'], $_POST['email'])) {
echo "Please enter all of the values!";
}else{
echo "Thanks,". $_POST['ign'].", you will receive an email when the site is complete!";
}
?>
You could use empty() as well, but it doesn't accept more than a variable at a time.
This is how I solved this issue:
$expression = $_POST['ign'] || $_POST['email'] ;
if (!isset($expression) {
echo "Please enter all of the values!";
}
else {
echo "Thanks, " . $_POST['ign'] . ", you will recieve an email when the site is
complete!";
}
Simplest way I know of:
<?php
if (isset($_POST['ign'], $_POST['email'])) {//do the fields exist
if($_POST['ign'] && $_POST['email']){ //do the fields contain data
echo ("Thanks, " . $_POST['ign'] . ", you will recieve an email when the site is complete!");
}
else {
echo ("Please enter all of the values!");
}
}
else {
echo ("Error in form data!");
}
?>
Edit: Corrected the code to show the form data and empty values errors seperatly.
Explanation: The first if statement checks that the submitted form contained two fields, ign and email. This is done to stop the second if statement , in the case that ign or email weren't passed in at all, from throwing an error(message would be printed to server logs). The second if statement checks the values of ign and email to see if they contain data.
Try this:
<?php
if (!isset($_POST['ign']) || isset($_POST['email'])) {
echo "Please enter all of the values!";
}
else {
echo "Thanks, " . $_POST['ign'] . ", you will recieve an email when the site is complete!";
}
?>
isset($_POST['ign'],$_POST['email']));
and then check for the empty values.
When you work with POST, use empty(). because when your form send data. It async null for empty input!
best way is that:
if ((!isset($_POST['ign']) || empty($_POST['ign'])) &&
(!isset($_POST['email']) || empty($_POST['email'])) {
YES! It's Ugly...
So you can use:
<?php
if ( checkInput($_POST['ign']) || checkInput($_POST['email']) ) {
echo "Please enter all of the values!";
}
else {
echo "Thanks, " . $_POST['ign'] . ", you will recieve an email when the site is complete!";
}
function checkInput($input){
return ( !isset($input) || empty($input) );
}
?>
You can try this code:
<?php
if(!isset($_POST['ign'], $_POST['email'])) {
echo "Please enter all of the values!";
} else {
echo "Thanks, " . $_POST['ign'] . ", you will receive an email when the site is complete!";
}
?>
// if any of this session is set then
if (isset($_SESSION['tusername']) || isset($_SESSION['student_login'])) {
it will return true;
} else {
it will return false;
}

having the hardest time passing NULL to my database

im working on a part of program where i need to send null to my database if the textbox is empty here is what i have so far
<?php
//so if not connected to database it displays an error message instead of a php error recommend having on 1 in development mode - for warnings and error
ini_set( "display_errors", 0);
if(!$_POST) exit;
$con = mysql_connect("localhost","imstillr","password");
mysql_select_db("imstillr_crm", $con);
$company = protect($_POST['company']); //required
$primarycontact = protect($_POST['primarycontact']); //required
$primaryemail = protect($_POST['primaryemail']); //required
$preferphone = protect($_POST['preferphone']); //required
$secondarycontact = protect($_POST['secondarycontact']);
$secondaryemail = protect($_POST['secondaryemail']);
$optionalphone = protect($_POST['optionalphone']);
$department = protect($_POST['department']);
$website = protect($_POST['website']); //required*/
//database info
mysql_query("SELECT companyname FROM customerinfo WHERE companyname='" .$company. "'");
if (!$con)
{
//checks if database connection string is correct
echo '<div class="error_message">Attention! no database connection.</div>';
exit();
} else if(mysql_affected_rows() == 1) {
echo '<div class="error_message">Attention! This company already exists.</div>';
exit();
} else if(trim($company) == '') {
echo '<div class="error_message">Attention! You must enter your company name.</div>';
exit();
} else if(trim($primarycontact) == '') {
echo '<div class="error_message">Attention! You must enter a contact name.</div>';
exit();
} else if(trim($primaryemail) == '') {
echo '<div class="error_message">Attention! Please enter a valid email address.</div>';
exit();
} else if(!isEmail($primaryemail)) {
echo '<div class="error_message">Attention! You have to enter an invalid e-mail address, try again.</div>';
exit();
} else if(trim($department) == '') {
echo '<div class="error_message">Attention! Please enter a department.</div>';
exit();
} else if(trim($preferphone) == '') {
echo '<div class="error_message">Attention! Please enter a preferred phone number.</div>';
exit();
} else if(!isPhone($preferphone)) {
echo '<div class="error_message">Attention! Please enter the right format for phone.</div>';
exit();
} else if(trim($website) == '') {
echo '<div class="error_message">Attention! Please enter a website name.</div>';
exit();
}
if($error == '') {
$secondarycontact = NULL;
$secondaryemail = 'random text';
$optionalphone = 'random text';
$address = "example#yahoo.com";
$clientaddress = $primaryemail;
//admin subject
$e_subject = $primarycontact .' has successfully been registered in the database';
//client subject
$c_subject = 'You have successfully been registered in the database';
/* another way of doing admin client email as array
$admin_email = array(
'e_body' => '$primarycontact has been registered in department '$department' \r\n\n',
'e_content' => 'You have been contacted by $name with regards to $subject, their additional message is as follows.\r\n\n';
'e_reply' => 'You can contact $primarycontact via email, $primaryemail';
);*/
//admin email
$e_body = "$primarycontact has been registered in department '$department' \r\n\n";
//$e_body = "You have been contacted by $name with regards to $subject, their additional message is as follows.\r\n\n";
$e_content = "Company Name: $company\n Primary Contact: $primarycontact\n Primary Email: $primaryemail\n Preferred Phone: $preferphone\n Secondary Contact: $secondarycontact\n Secondary Email: $secondaryemail\n Optional Phone: $optionalphone\n Department: $department\n Website: $website \r\n\n";
//$e_content = "\"anything can be displayed here such as all the customers entered info\"\r\n\n";
$e_reply = "You can contact $primarycontact via email, $primaryemail ";
//client email
$c_body = "You has been registered in department '$department' \r\n\n";
$c_content = "Company Name: $company\n Primary Contact: $primarycontact\n Primary Email: $primaryemail\n Preferred Phone: $preferphone\n Secondary Contact: $secondarycontact\n Secondary Email: $secondaryemail\n Optional Phone: $optionalphone\n Department: $department\n Website: $website \r\n\n";
$c_reply = "For anymore information feel free to contact the administrator vis email, $address";
//admin msg
$msg = $e_body . $e_content . $e_reply;
//client msg
$cmsg = $c_body . $c_content . $c_reply;
//inserts information
mysql_query("INSERT INTO `imstillr_crm`.`customerinfo` (`id`, `companyname`, `primarycontact`, `primaryemail`, `prefphone`, `secondarycontact`, `secondaryemail`, `optionalphone`, `department`, `website`) VALUES (NULL, '".$company."', '".$primarycontact."', '".$primaryemail."', '".$preferphone."', '".$secondarycontact."', '".$secondaryemail."', '".$optionalphone."', '".$department."', '".$website."')");
if(mail($address, $e_subject, $msg, "From: $primaryemail\r\nReply-To: $primaryemail\r\nReturn-Path: $primaryemail\r\n")) {
//if mail was sent to admin then send to person who signed up
mail($primaryemail, $c_subject, $cmsg, "From: $address\r\nReply-To: $address\r\nReturn-Path: $address\r\n");
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo $secondarycontact. '<br />';
echo $secondaryemail. '<br />';
echo $optionalphone. '<br />';
//echo "<h1>User $primarycontact Successfully added onto '$department'.</h1>";
echo "<p>Thank you <strong>$primarycontact</strong>, your registration info has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
}
//all functions go here
//protects database from SQL injection
function protect($value) {
if(get_magic_quotes_gpc()){
return mysql_real_escape_string(stripslashes($value));
}else{
return mysql_real_escape_string($value);
}
}
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
function isPhone($number) {
return(preg_match("/^([\(]{1}[0-9]{3}[\)]{1}[ ]{1}[0-9]{3}[\-]{1}[0-9]{4})$/",$number));
}
?>
optionalphone,secondaryemail and secondarycontact are the only values that can be null
This will not work:
$foo = null;
mysql_query("INSERT INTO ... VALUES (".$foo.")");
This will:
mysql_query("INSERT INTO ... VALUES (NULL)");
So you might want to do it this way:
function quoted_string_or_null($var) {
return $var === null ? 'NULL' : "'".$var."'";
}
$foo = null;
mysql_query("INSERT INTO ... VALUES (".quoted_string_or_null($foo).")");
However, there is another problem: there is no way you will be getting real null values from your protect function or from $_POST. So you have to decide if an empty string is a legal value, or if empty strings should be converted to null. It's probably the latter, so you can make a small change and work with this:
function quoted_string_or_null($var) {
return ($var === null || $var === '') ? 'NULL' : "'".$var."'";
}
Rather than manually quoting the strings, use something to do this for you. See http://php.net/manual/en/function.mysql-real-escape-string.php
In the comments is a function written for your issue:
<?php
function db_escape($values, $quotes = true) {
if (is_array($values)) {
foreach ($values as $key => $value) {
$values[$key] = db_escape($value, $quotes);
}
}
else if ($values === null) {
$values = 'NULL';
}
else if (is_bool($values)) {
$values = $values ? 1 : 0;
}
else if (!is_numeric($values)) {
$values = mysql_real_escape_string($values);
if ($quotes) {
$values = '"' . $values . '"';
}
}
return $values;
}
?>
Once you have escaped each value, pass it without any extra quotes to the insert command.

foreach invalid argument and undefined variable

I am trying to create a form and i get an error in these lines.
else
{
//report the errors.
echo '<h1> Err... </h1>
<p> The following error(s) have occured</p>';
foreach ($errors as $msg)
{
echo "--$msg<br />\n";
}
echo '</p><p>Please Try Again.</p><p><br/></p>';
}
So, what's wrong?? Here's the error message -
Err...
The following error(s) have occured -
Notice: Undefined variable: errors in
C:\wamp\www\password.php on line 107
Warning: Invalid argument supplied for
foreach() in C:\wamp\www\password.php
on line 107 Please Try Again.
I have set errors as an array.
My code above --
if(isset($_POST['submitted']))
{
require_once('C:\wamp\www\connect.php');
//connecting to db
$errors = array();
if (empty($_POST['email']))
{
$errors[]='Please enter a valid email address.';
}
Here is my complete code -
//forgot password update
include('C:\wamp\www\header.html');
//check if form has been submitted
require_once('C:\wamp\www\connect.php');
//connecting to db
if(isset($_POST['submitted'])) {
$errors = array();
if (empty($_POST['email']))
{
$errors[]='Please enter a valid email address.';
}
else
{
$e = mysqli_real_escape_string($db_name,trim($_POST['email']));
}
//check for current password
if (empty($_POST['password']))
{
$errors[]='Current password does not match.';
}
else
{
$p = mysqli_real_escape_string($db_name,trim($_POST['password']));
}
//check for a new password and match with confirm pass.
if(!empty($_POST['password1']))
{
if($_POST['password1'] != $_POST['cpass'])
{
$errors[] = 'The entered password and confirm password do not match.';
}
else
{
$np=mysqli_real_escape_string($db_name,trim($_POST['password1']));
}
}
if(empty($errors))
//if everything is fine.
//verify the entered email address and password.
$q="SELECT username FROM users WHERE (email='$e' AND password=SHA1('$p'))";
$r=#mysqli_query($db_name,$q);
$num = #mysqli_num_rows($r);
if($num==1)
//if it matches.
//get user id
{
$row=mysqli_fetch_array($r, MYSQLI_NUM);
//udpdate query.
$q="UPDATE users SET password= SHA1('$np') WHERE username=$row[0]";
$r=#mysqli_query($db_name, $q);
if (mysqli_affected_rows($db_name) ==1)
{
echo '<h3>Your password has been updated.</h3>';
}
else {
echo '<h3>Whops! Your password cannot be changed due a system error. Try again later. Sorry</h3>';
echo '<p>' .mysqli_error($db_name). 'Query:' . $q.'</p>';
}
exit();
}
else
{
//invalid email and password
echo 'The email address and password do not match';
}
}
else
{
//report the errors.
echo '<h1> Err... </h1>
<p> The following error(s) have occured</p>';
foreach ($errors as $msg)
{
echo "--$msg<br />\n";
}
echo '</p><p>Please Try Again.</p><p><br/></p>';
}
?>
There is no array named $errors. You will have to look further up your script why not.
You can fix the error message by using
if (!empty($errors) and (is_array($errors)))
foreach ($errors as $msg)
Your foreach loop is out of the scope in regards to where the $error array is defined.
Your code in a nutshell:
if(isset($_POST['submitted'])) {
$errors = array();
} else {
foreach($errors as $error)
}
If $_POST is not set, than your $errors is not defined.
Move your declaration for "$errors = array()" above the line "if(isset($_POST['submitted'])) {
" and everything should work fine!
You have two problems. The first is the cause of the empty/non-existent array and the second is a lack of testing for it.
The first is that you are testing for errors inside of an if block and then looping through them inside of the else block.
if (isset($_POST['submitted'])) {
// create errors array and set errors
} else {
// loop through array of errors
}
So if errors are set, the script doesn't make it to the loop. If the script makes it to the loop, no errors were set.
The second is that you should only enter the foreach loop after you have tested the array:
if (!empty($errors) && is_array($errors)) { // use this line and get rid of the else.
foreach ($errors as $msg) {
echo "--$msg<br />\n";
}
echo '</p><p>Please Try Again.</p><p><br/></p>';
} // and close it.
Basically, what's happening here is you're using $errors before it is defined.
It may be that you need to set "$errors = array( )" near the top of your script so that it is always at least an empty array.

Categories