This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 9 years ago.
Error!
The following error(s) occurred:
Notice: Undefined variable: errors in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC9\data\localweb\scripts\ladies_paradise\checkout.php on line 75
Please try again.
`
Untitled Document
<body>
<?php
$page_title='ORDER FORM';
if(isset($_POST['submitted'])){
$errors= array();
$price=($_POST['price']);;
$quantity=($_POST['quantity']);
$total = $quantity * $price;
$total = number_format ($total, 2);
// Validate the name and combat Magic Quotes, if necessary.
if (empty ($_POST['product'])) {
$errors[]='You forgot to enter product.';
}else{
$pr=trim($_POST['product']);
}
// Validate the price.
if (empty ($_POST['price'])) {
$errors[] ='You forgot to enter price.';
} else {
$p=trim($_POST['price']);
}
// Validate the quantity.
if (empty ($_POST['quantity'])) {
$errors[] ='You forgot to enter quantity.';
} else {
$q=trim($_POST['quantity']);
}
if(empty($errors)){
require_once('checkout_connect.php');
$query="INSERT INTO customers(product,price,quantity)VALUES('$pr','$p','$q')";
$result=#mysql_query($query);//Run the query.
if($result){
echo 'You are purchasing <b>', $c. '</b>.
Total price is <b>$', $total, '</b>.';
} else { // One from element was not filled out properly.
echo '<p><font color="orange">Please go back and fill out the form again.</font></p>';
}
exit();
}else{ //If it did not run OK.
echo '<h1 id="mainhead">System Error</h1>
<p class="error">You could not registered due to system error.We apologize for any inconvenience.</p>';//Public message.
echo '<p>'.mysql_error().'<br/><br/>'.$query.'</p>'; //Debugging message.
exit();
}
mysql_close(); //Close the database connection.
}else{ //Report the errors.
echo '<h1 id="mainhead">Error!</h1>
<p class="error">The following error(s) occurred:<br />';
if (is_array($errors)) {
foreach ($errors as $msg){ //Print each error.
echo " - $msg<br />\n";
}
}
echo '</p><p>Please try again.</p><p><br /></p>';
}//End of if (empty($errors)) IF.
?>
<h2>ORDER FORM:</h2>
<form action="checkout.php" method="post">
<p>Product: <input type="number" name="code_item" size="15" maxlength="15" value"<?php if (isset($_POST['product'])) echo $_POST['product']; ?>" /></p>
<p>Price: <input type="number" name="price" size="15" maxlength="30" value"<?php if (isset($_POST['price'])) echo $_POST['price']; ?>" /></p>
<p>Quantity: <input type="number" name="quantity" size="30" maxlength="50" value"<?php if (isset($_POST['quantity'])) echo $_POST['quantity']; ?>" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="submitted" value="TRUE" />
</form>
</body>
</html>``
Define it at the top of the document.
<?php
$errors = false;
Alternatively, check if it is set using a ternary where assignment is necessary.
echo isset($errors) ? $errors: '';
Where '' can be replaced with whatever assignment correlates to the requirements.
Related
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I have been following the w3schools php tutorial to produce a form. The form collects and displays data but none of the error checking is working. I have run the php and html through lint with no errors and double checked my use of quotes.
Specifically the script is not applying htmlspecialchars, trim or split. None of the regex checking is being applied and the error messages are not appearing. I tried replacing an error message with a simple if / not echo message and that worked, although the message was placed at the head of the web page, not next to the field.
I am also getting the following on execution.
Notice: Undefined index: numChild in /volume1/homes/richard/www/action.php on line 22
Line 22 is:
$totalGuests = $_POST['numAdults'] =+ $_POST['numChild'];
The difference between this and other undefined index questions is that the function 'test_input' is not being applied. I have included #Poiz suggestion below and this resolves the undefined index problem but the function is still now working.
My code is:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
// define variables and set to empty values
$guestName = $guestEmail = $guestPhone = $startDate = $endDate = $numAdults = $numChild = "";
$guestNameErr = $guestEmailErr = $guestPhoneErr = $startDateErr = $endDateErr = $numAdultsErr = $numChildErr = "";
$maxAllowed = 4;
$totalGuests = $_POST['numAdults'] =+ $_POST['numChild'];
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (empty($_POST['guestName'])) {
$guestNameErr = "guestName is required";
} else {
$guestName = test_input($_POST['guestName']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$guestName)) {
$guestNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST['guestEmail'])) {
$guestEmailErr = "Email is required";
} else {
$guestEmail = test_input($_POST['guestEmail']);
// check if e-mail address is well-formed
if (!filter_var($guestEmail, FILTER_VALIDATE_EMAIL)) {
$guestEmailErr = "Invalid guest email format";
}
}
if (empty($_POST['guestPhone'])) {
$guestPhoneErr = "Phone number is required";
} else {
$guestPhone = test_input($_POST['guestPhone']);
// check if phone number is UK format and valid
if (!preg_match("/^(\+44\s?7\d{3}|\(?07\d{3}\)?)\s?\d{3}\s?\d{3}$/",$guestPhone)) {
$guestPhoneErr = "Please enter a valid phone number";
}
}
if (empty($_POST['startDate'])) {
$startDateErr = "Start date is required";
} else {
$startDate = $_POST['startDate'];
}
if (empty($_POST['endDate'])) {
$endDateErr = "Start date is required";
} else {
$endDate = $_POST['endDate'];
if ($_POST['endDate'] < $_POST['startDate']) {
$sendDateErr = "End date must be before start date";
}
}
if ($totalGuests > $maxAllowed) {
$bookingErr = "A maximum of 4 guests can be accommodated at Mariner's Loft";
} else {
$numAdults = ($_POST['numAdults']);
$numChild = ($_POST['numChild']);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<br><input type="text" class="form-control" id="guestName" name="guestName" value="<?php echo $guestName;?>" placeholder="Full name" autofocus required>
<br>
<br><input type="email" class="form-control" id="guestEmail" name="guestEmail" value="<?php echo $guestEmail;?>" placeholder="email">
<br>
<br><input type="phone" class="form-control" id="guestPhone" name="guestPhone" value="<?php echo $guestPhone;?>" placeholder="Phone number">
<p><strong>How many guests?</strong></p>
<p>How many adults?</p>
<br><input type="text" class="form-control" id="numAdults" name="numAdults" value="<?php echo $numAdults;?>" placeholder="number of adults">
<p>How many children?</p>
<br><input type="text" class="form-control" id="numChild" name="numChild" value="<?php echo $numChild;?>" placeholder="number of children">
<br>
<br><input type="date" class="form-control" id="startDate" name="startDate" value="<?php echo $startDate;?>" placeholder="Arrival date">
<br>
<br><input type="date" class="form-control" id="endDate" name="endDate" value="<?php echo $endDate;?>" placeholder="Leaving date">
<br><br>
<input type="submit" name="submit" value= "Submit"/>
<br><br>
<input type="reset" name="submit" value="Cancel"/>
</form>
<?php
echo "<h2>Guest info:</h2>";
echo $guestName;
echo "<br>";
echo $guestEmail;
echo "<br>";
echo $guestPhone;
echo "<br>";
echo $totalGuests;
echo "<br>";
echo $startDate;
echo "<br>";
echo $endDate;
?>
</body>
</html>
Any help gratefully received.
The Code $totalGuests = $_POST['numAdults'] =+ $_POST['numChild']; should be moved into the Conditional Block or redeclared to have a Default: (1, for example)...
$maxAllowed = 4;
$totalGuests = ( isset($_POST['numAdults'] ) &&
isset($_POST['numChild']) ) ?
( $_POST['numAdults'] + $_POST['numChild'] )
:1;
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// REST OF THE CODES
}
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
Hello everyone!
can someone guide me for the following problem? I was trying to make a php form, but it shows the error ( Undefined index: firstname in C:\xampp\htdocs\form_require1.php on line 53/55) when I run it. please help me
enter code here <?php // define valiables and set to empty values $firstnameErr = $lastnameErr = ""; $firstname = $lastname = ""; if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "Name is required";
} else {
$firstname = test_input($_POST["firstname"]); }
if (empty($_POST["lastname"])){
$lastnameErr = "Name is require"; } else { $lastname = test_input($_POST["lastname"]); } } function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
return $data; } ?> `enter code here` <form action="<?php echo htmlentities($_SERVER["PHP_SELF"]) ?>" method="post"> Your firstname <input type="text" name="firstname" /> <span class="error">* <?php echo $firstnameErr;?></span> <br><br> Your Lastname <input type="text" name="lastname" /> <span class="error">* <?php echo $lastnameErr;?></span> <br><br> <input type="submit" value="Submit" /> </form> <?php // } else {
echo 'Your Details';
echo "<br>";
echo 'Fistname: ' . $_POST["firstname"];
echo "<br>";
echo 'Lastname: ' . $_POST["lastname"];
Basically the $_POST variables you want to use are not set. To be sure the form passes the right variables use var_dump($_POST); to see what variables it passes on.
For more information about your error see: php notice undefined variable and notice undefined index
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
So here is my form I use to get the email and password, don't mind all the tabs xD.
<form method="post" action="">
<ul>
<label for='usermail'>email </label>
<input type='text' name='email' placeholder="jouwnaam#mail.nl" required>
</ul>
<ul>
<label for="password">Wachtwoord</label>
<input type="password" name="wachtwoord" placeholder="wachtwoord" required>
</ul>
<ul>
<div class='login-btn btn btn-default btn-lg'><input name="submit" type="submit" value="Inloggen"></div>
</ul>
</form>
And this is my PHP code:
<?php
if (isset($_POST['inloggen']))
{
mysql_connect("localhost","root","usbw") or die('error');
mysql_select_db("sportschool") or die('error');
$k_email = $_POST['email'];
$wachtwoord = $_POST['wachtwoord'];
echo $k_email;
if (mysql_query("SELECT * FROM klant;") == false)
{
echo mysql_error();
}
else
{
$resultaat = mysql_query("SELECT wachtwoord FROM klanten WHERE email='".$k_code."';");
$data = mysql_fetch_assoc($resultaat);
echo "<br />";
echo "<br />";
$k_wachtwoord = $data["wachtwoord"];
echo $k_wachtwoord;
if ($wachtwoord==$k_wachtwoord)
{
echo "U are logged in";
session_start();
$_SESSION['ingelogd'] = true;
$_SESSION['klantemail'] = $k_email;
}
else
{
echo "Username or Password is not right try again.";
}
echo "<br />";
mysql_close();
}
}
?>
Every time I login with the correct email and password the page is refreshed but I don't get the echo for logged in or the error for not logging in.
I have this PHP code which checks if the user is logged in, and that one stays on not logged in:
<?php
if ((isset($_SESSION['ingelogd'])) && ($_SESSION['ingelogd'] == true))
{
echo $_SESSION['klantemail']." is ingelogd";
}
else
{
echo "Nog niet ingelogd.";
}
?>
I don't use PHP a lot, so there may be a lot of mistakes.
Replace this code
if (isset($_POST['inloggen']))
with
if (isset($_POST['submit']))
Your are not checking the correct value.
Try:
if (isset($_POST['submit']) && $_POST['submit'] == "Inloggen")
The key to the post variable is the name attribute of the submit button while its value would be inloggen.
So it should be:
if (isset($_POST['submit']))
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
I get Undefined index: image error in this code. Can I know the exact solution? I wanna know workflow from line abc to xyz that I commented in the code using //.Thanks for your help..
<?php session_start();
include("config.php");
if(isset($_SESSION['name']))
{
if(!$_SESSION['name']=='admin')
{
header("Location:login.php?id=You are not authorised to access this page unless you are administrator of this website");
}
}
?>
<?php
$name=$_FILES['image']['name'];
$tmp=$_FILES['image']['tmp_name'];
$err=$_FILES['image']['error'];
}
if($err==0)
{
move_uploaded_file($tmp, $name);
//xyz}
$category=$_POST['category'];
$title=$_POST['title'];
$image=$_FILES["image"]["name"];
$content=$_POST['content'];
}
<?php
$qry=mysql_query("INSERT INTO articles(title,image,content,category)VALUES('$title','$image','$content','$category')");
if(!$qry)
{
die("Query Failed: ". mysql_error());
}
else
{
echo "Article Added Successfully";
}
?>
The form code is here:
<?php
include("config.php");
$sql=mysql_query("select * from category");
if(!$sql)
{
mysql_error();
}
?>
<form action="created_article.php" method="post">
Category:
<select name="category">
<?php
while($row=mysql_fetch_array($sql))
{
echo"<option value='".$row['category']."'>".$row['category']."</option>";
}
?>
</select>
Title:
<input type="text" name="title"/>
Upload Image:
<input type="file" name="image" id="image" />
Contents:
<textarea name="content" cols="100" rows="12" ></textarea>
<input type="submit" name="button" value="Submit" />
</form>
I need help with these code, I need to make project and I'm stuck here, so please kindly I request for your help,
<form action="created_article.php" method="post" enctype="multipart/form-data">
define enctype in your form tag otherwise its not work for image
While Dealing with input File always put form attribute enctype='multipart/form-data'
<?php
session_start ();
include ("config.php");
if (isset ( $_SESSION ['name'] )) {
if (! $_SESSION ['name'] == 'admin') {
header ( "Location:login.php?id=You are not authorised to access this page unless you are administrator of this website" );
}
}
if (!empty($_POST))
{
$name = $_FILES ['image'] ['name'];
$tmp = $_FILES ['image'] ['tmp_name'];
$err = $_FILES ['image'] ['error'];
if($err==0) {
move_uploaded_file($tmp, $name);
$category=$_POST['category'];
$title=$_POST['title'];
$image=$_FILES["image"]["name"];
$content=$_POST['content'];
}
$qry=mysql_query("INSERT INTO articles(title,image,content,category)VALUES('$title','$image','$content','$category')");
if(!$qry){
die("Query Failed: ". mysql_error());
} else {
echo "Article Added Successfully";
}
}
include("config.php");
$sql=mysql_query("select * from category");
if(!$sql){
mysql_error();
}
?>
The form code is here:
<form action="created_article.php" enctype='multipart/form-data' method="post">
Category: <select name="category">
<?php
while($row=mysql_fetch_array($sql))
{
echo"<option value='".$row['category']."'>".$row['category']."</option>";
}
?>
</select> Title: <input type="text" name="title" /> Upload Image: <input
type="file" name="image" id="image" /> Contents:
<textarea name="content" cols="100" rows="12"></textarea>
<input type="submit" name="button" value="Submit" />
</form>
I´m trying to do a login form with php but I´m having an issue that I´m not finding where is the error.
When I submit the form with the correct data I´m having this erros:
Error one:
-> Warning: Invalid argument supplied for foreach() :
`foreach($query as $autUser);`
Error two:
-> Notice: Undefined variable: autUser here
if($autEmail == $autUser['email'] && $autSenha == $autUser['senha'])
And also gives me the error 'Wrong Pass' and I put the correct answer.
Somebody there have exprience with this errors?
Can you see some error?
My php:
<?php if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['pass']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'Pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$query = "SELECT * FROM users where email= '$autEmail'";
$exeqr = mysql_query($query) or die(mysql_error());
if($query)
{
foreach($query as $autUser);
if($autEmail == $autUser['email'] && $pass == $autUser['pass'])
{
echo 'Login Sucess';
}
else
{
echo ' Wrong Pass';
}
}
else
{
echo 'Informed email does not exist';
}
}
}
?>
My html:
<form name="login" action="" method="post">
<label>
<span>E-mail:</span>
<input type="text" class="radius" name="email" value="<?php if(isset($f['email'])) echo $f['email']; ?>" />
</label>
<label>
<span>Password:</span>
<input type="password" class="radius" name="pass" value="<?php if(isset($f['pass'])) echo $f['pass']; ?>" />
</label>
<input type="submit" value="Login" name="sendLogin" class="btn" />
</form>
I'd suggest the following:
Don't use mysql - use mysqli or PDO instead
echo out/dump $autEmail variable and see what it holds
copy the query and test it with no PHP code (via phpMyAdmin for example or command line sql)
Try changing the comparison used to if(mysql_num_rows($exeqr) === 0)