Undefined variable and Undefined index errors - php

The program I'm working on is supposed to remove dashes, spaces, etc.. from an input box and display the number back to the user.
I am getting an undefined variable and undefined index error in my php code. The errors are on line 35 and 41. I'm guessing the function is out of scope, but I'm not sure.
I made factorial calculator with similar code and it worked fine. I've tried adapting that code to this problem, but I can't get it to work. I don't know why, but I'm having quite a bit of trouble getting an understanding of how php works.
Thanks!
<?php
function getCardNum($cardNum) {
$ccNum = true;
if ($_POST) {
$number = $_POST['cardNum'];
$number = preg_replace('/[\-\" "]/', '', $number);
if (is_numeric($number)) {
$ccNum = true;
}
else {
$ccNum = false;
}
return $number;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Card Validator</title>
<link rel="stylesheet" type="text/css" href="common.css" />
</head>
<body>
<h3>Enter your credit card number!:</h3>
<form method="POST">
<table border="0">
<tr>
<td>Enter numeric character only</td>
<td><input type="text" name="cardNum" id="cardNum" size = "50" /></td>
<td>
<?php
if ($cardNum) {
echo '<p style="color:green;">Number is valid</p>';
echo '<p style="color:green;">' . getCardNum($_POST['cardNum']) . '</p>';
}
else {
echo '<p style="color:red;">Number contains non-numeric characters!</p><br />';
echo '<p style="color:red;">' . getCardNum($_POST['cardNum']) . '</p>';
}
?>
</td>
</tr>
<td><input type="submit" name="cardNum" id="cardNum" value="Submit" /></td>
<td><input type="reset" name="resetButton" id="resetButton" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>

if ($_POST) { will always evaluate to true, because $_POST superglobal exists all the time. you will have to do more specific test like if (isset($_POST['cardNum']))

I had to change a few of the conditions, but I think this should work as expected.
The submit input was renamed to submit because it was causing a conflict.
Added if (is_numeric($_POST['cardNum'])) {
and if ((!is_numeric($_POST['cardNum'])) && (isset($_POST['cardNum']))) {
<?php
function getCardNum() {
$ccNum = true;
if(isset($_POST['submit'])) {
$number = $_POST['cardNum'];
$number = preg_replace('/[\-\" "]/', '', $number);
if (is_numeric($number)) {
$ccNum = true;
}
else {
$ccNum = false;
}
return $number;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Card Validator</title>
<link rel="stylesheet" type="text/css" href="common.css" />
</head>
<body>
<h3>Enter your credit card number!:</h3>
<form method="POST" action="">
<table border="0">
<tr>
<td>Enter numeric character only</td>
<td><input type="text" name="cardNum" id="cardNum" size = "50" /></td>
<td>
<?php
if (is_numeric($_POST['cardNum'])) {
echo '<p style="color:green;">Number is valid</p>';
echo '<p style="color:green;">' . getCardNum($_POST['cardNum']) . '</p>';
}
if ((!is_numeric($_POST['cardNum'])) && (isset($_POST['cardNum']))) {
echo '<p style="color:red;">Number contains non-numeric characters!</p><br />';
echo '<p style="color:red;">' . getCardNum($_POST['cardNum']) . '</p>';
}
?>
</td>
</tr>
<td><input type="submit" name="submit" id="cardNum" value="Submit" /></td>
<td><input type="reset" name="resetButton" id="resetButton" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>

Use the isset() function before you address keys that you're not sure they exist in an array.
For instance:
if (isset($_POST['cardNum'])) {
echo '<p style="color:green;">Number is valid</p>';
echo '<p style="color:green;">' . getCardNum($_POST['cardNum']) . '</p>';
}

Related

More than one row does not inserted into database..PHP and jQuery

I have created dynamic table from where I can insert data into database, But problem is that when I try to insert more than 1 row into database, its goes nowhere. As I have tried to insert only 1 row as its inserting successfully which advice me what I'm doing wrong
<?php
include "includes/config.php";
?>
<?php
$error_array = array();
$name = $email = $phone = $name_Error = $email_Error =$phone_Error ="";
if(isset($_POST['save_all']))
{
if($_POST['name'] !="")
{
$name = $_POST['name'];
}
else
{
$name_Error ="Enter name";
array_push($error_array,$name_Error);
}
if($_POST['email'] !="")
{
$email = $_POST['email'];
}
else
{
$email_Error ="Enter email";
array_push($error_array,$email_Error);
}
if($_POST['phone'] !="")
{
$phone = $_POST['phone'];
}
else
{
$phone_Error ="Enter phone";
array_push($error_array,$phone_Error);
}
if(count($error_array) == 0)
{
$insert_user = "INSERT INTO users(user_id,name,email,phone) values(NULL,'$name','$email','$phone')";
$res_users = mysqli_query($link,$insert_user);
if($res_users >0)
{
$success_Message = "record inserted";
array_push($error_array,$success_Message);
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="<?php echo CSS_URL;?>add_more.css">
<script src="<?php echo JS_URL;?>jquery.js"></script>
<title>Add More</title>
<script>
$(document).ready(function()
{
var count = 1;
$(".addmore_Button").click(function()
{
count++;
$(".addmore_Form_Table").append('<tr><td class="serial_num"><span>'+count+'</span></td><td><input type="text" name="name"/></td><td><input type="text" name="email"/></td><td><input type="text" name="phone"/></td><td><img id="delete'+count+'" style="margin-left:35px; margin-right:10px" onclick="deleteRow(this.id);" src="images/delete (1).png" /></tr>');
});
});
function deleteRow(id)
{
confirm("Are you sure you want to delete...?");
$("#"+id).parent().parent().parent().remove();
}
$(document).ready(function()
{
$("#delete_User").on('click',function()
{
alert("Sorry, you cant delete first row...!!");
});
});
</script>
</head>
<body>
<table class="addmore_Table">
<tr>
<th class="heading">Sr.No</th>
<th class="heading">Email</th>
<th class="heading">Name</th>
<th class="heading">Phone</th>
<td><input type="submit" class="addmore_Button" name="addmore_Button" value="Add More" /></td>
</tr>
</table>
<form name="addmore_Form" action="" method="post" class="addmore_Form">
<table class="addmore_Form_Table">
<tr>
<td></td>
<td><?php echo $name_Error;?></td>
<td><?php echo $email_Error;?></td>
<td><?php echo $phone_Error;?></td>
<td></td>
</tr>
<tr>
<td class="serial_num"><span>1</span></td>
<td><input type="text" name="name" value="<?php echo $name;?>" /></td>
<td><input type="text" name="email" value="<?php echo $email;?>" /></td>
<td><input type="text" name="phone" value="<?php echo $phone;?>" /></td>
<td><img id="delete_User" style="margin-left:35px; margin-right:10px" src="images/delete (1).png" /></td>
</tr>
</table>
<input type="submit" class="save_all" name="save_all" value="Save All" />
</form>
</body>
</html>

PHP form forgets values when uploading large files

Title says it all...I have a contact form that allows four files to be uploaded. If you upload large files, the form actually "forgets" name, phone number, e-mail, etc. At least, I get the error screen telling the user to provide that info, and I don't get the e-mail message.
If I use small files (like, say, a megabyte or less), it works fine, and I get the files, but any more bandwidth and it's like I'm submitting a blank form, even though it goes through the motion of uploading the files (it takes well over a minute before I get the error page).
Here's the source of the form itself, including some PHP:
<?php
ini_set("max_input_time","5");
ini_set("max_execution_time","1");
ini_set("upload_max_filesize","2048M");
ini_set("post_max_size","2048M");
?>
<html>
<head>
<script language="Javascript">
function formValidate() {
// Did the user include a name?
var userName=document.forms["contactRich"]["cName"].value;
if (userName=="" || userName==null) {
alert("Please provide your name.");
return false;
}
// Did the user include a phone number and area code?
var phoneNumber=document.forms["contactRich"]["cNumber"].value;
var areaCode=document.forms["contactRich"]["cAreaCode"].value;
if (phoneNumber=="" || phoneNumber==null || areaCode=="" || areaCode==null) {
alert("Please include your phone number with the area code.");
return false;
}
// Did the user provide a valid e-mail address?
var emailAddress=document.forms["contactRich"]["cEmail"].value;
var atCount=emailAddress.split("#").length-1;
var lastAt=emailAddress.lastIndexOf("#");
var isDot=emailAddress.lastIndexOf(".");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(emailAddress) || emailAddress=="" || emailAddress==null || emailAddress.length<5 || lastAt <0 || isDot<0 || isDot<lastAt || atCount!=1) {
alert("Please provide a valid e-mail address.");
return false;
}
// Did the user select a service?
if (document.forms["contactRich"]["cTopic"].value=="null") {
alert("Please tell us what you need help with.");
return false;
}
document.getElementById("isValid").value="yes";
return true;
}
</script>
<!-- #BeginEditable "doctitle" -->
<title>Contact Rich</title>
<!-- #EndEditable -->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.form { font-family: "Franklin Gothic Medium", "Trebuchet MS"; font-size: 13pt}
-->
</style>
</head>
<body bgcolor="#CCCCCC">
<table width="800" border="0" cellspacing="2" cellpadding="2" align="center" bgcolor="#FFFFFF">
<form name="contactRich" id="contactRich" method="post" action="formHandler2.php" enctype="multipart/form-data" onsubmit="return fabFormValidate()">
<table cellpadding="6">
<tr>
<td colspan="2"><h3>Contact</h3></td>
</tr>
<tr>
<td class="form">Your name:</td>
<td><input type="text" name="cName" size="31"></td>
</tr>
<tr>
<td class="form">Your phone number:<br /><span class="footer">(Include area code)</span></td>
<td>(<input type="text" size="3" maxlength="3" name="cAreaCode"/>) <input type="text" id="cNumber" name="cNumber" size="23"></td>
</tr>
<tr>
<td class="form">Your e-mail address:</td>
<td><input type="text" name="cEmail" size="31"></td>
</tr>
<tr>
<td class="form">What can we help you with?</td>
<td><select name="cTopic">
<option value="null">(Please choose:)</option>
<option value="an estimate">Estimate</option>
<option value="bifold doors">Bifold doors</option>
<option value="broken window ropes">Broken window ropes</option>
<option value="door that won't stay shut">My door won't stay shut!</option>
<option value="noisy doors">My door is noisy!</option>
<option value="sticking doors">My door is sticking!</option>
<option value="drywall repairs">Drywall repairs</option>
<option value="garbage disposals">Garbage disposals</option>
<option value="grab bars">Grab bars</option>
<option value="your various services">(other)</option>
</select></td>
</tr>
<tr>
<td class="form">Any additional details?</td>
<td><textarea name="cAdditional" cols="27" rows="4" wrap="soft"></textarea></td>
</tr>
<tr>
<td class="form">You may include up to<br />four pictures:</td>
<td>
<input type="file" name="file_1" id="file_1" /><br />
<input type="file" name="file_2" id="file_2" /><br />
<input type="file" name="file_3" id="file_3" /><br />
<input type="file" name="file_4" id="file_4" /><br />
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
<tr>
<td colspan="2"><hr /></td>
</tr>
</table>
<input type="hidden" id="isValid" name="isValid" value="no" />
</form>
</table>
<p> </p>
</body>
</html>
Here's the PHP that actually processes the data and tries to send it, via PHPMailer:
<?php
ini_set("max_input_time","5");
ini_set("max_execution_time","1");
ini_set("upload_max_filesize","2048M");
ini_set("post_max_size","2048M");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php
$error_exists = false;
$masterEmail = "email#goes.here";
require 'PHPMailer-master/PHPMailerAutoload.php';
include "Form.php";
$name = $_POST['cName'];
$areaCode = $_POST['cAreaCode'];
$phone = $_POST['cNumber'];
$email = $_POST['cEmail'];
$from = "from_address#goes.here";
$topic = "(WEB) ".$_POST['cTopic'];
$additional = $_POST['cAdditional'];
$isValid = $_POST['isValid'];
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r<br /> <br />";
$body = "Name: ".$name."<br /> <br />";
$body = $body."Phone number: (".$areaCode.") ".$phone."<br /> <br />";
$body = $body."E-mail address: ".$email."<br /> <br />";
$body = $body."Needs help with: ".$topic."<br /> <br />";
if (!empty($additional)) {
$body = $body .$additional;
}
$body .= "\n\nIP address: ".$_SERVER['REMOTE_ADDR']."<br /> <br />";
$body .= "Browser: ".$_SERVER['HTTP_USER_AGENT']."<br /> <br />";
$mail = new PHPMailer();
$mail->addAddress($masterEmail);
$mail->setFrom($email, $from);
$mail->Subject = $subject;
$mail->msgHTML($body);
if (isset($_FILES['file_1'])) {
$mail->addAttachment($_FILES['file_1']['tmp_name'],$_FILES['file_1']['name']);
}
if (isset($_FILES['file_2'])) {
$mail->addAttachment($_FILES['file_2']['tmp_name'],$_FILES['file_2']['name']);
}
if (isset($_FILES['file_3'])) {
$mail->addAttachment($_FILES['file_3']['tmp_name'],$_FILES['file_3']['name']);
}
if (isset($_FILES['file_4'])) {
$mail->addAttachment($_FILES['file_4']['tmp_name'],$_FILES['file_4']['name']);
}
if (empty($name)) {
$errors = "Please provide your name.<br />";
$error_exists = true;
}
if (!ctype_digit($areaCode) || strlen($areaCode) != 3 || strlen($phone) < 7) {
$errors .= "Please provide your phone number, including area code.<br />";
$error_exists = true;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "Please enter a valid e-mail address.<br />";
$error_exists = true;
}
if (empty($topic)) {
$errors .= "Please tell us what you need help with.<br/>";
$error_exists = true;
}
?>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<title>Request for Information</title>
</head>
<body bgcolor="#cccccc">
<?php
$f=new fabForm();
$f->setSubject($subject);
$f->setBody($body);
$f->setEmail($email);
$f->setFrom($from);
?>
<p> </p>
<table align="center" bgcolor="#FFFFFF">
<tr>
<td>
<?php
if ($error_exists) {
echo $errors;
echo " <br />";
echo "<a href='contact.php'>Click here to try again.</a>";
} else {
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
</td>
</tr>
</table>
</body>
</html>
Finally, here's the form class I'm using:
<?php
class Form {
private $email;
private $subject;
private $body;
private $from;
private $headers;
// SET methods
public function setEmail($emailAddress) {
$this->email=$emailAddress;
}
public function setSubject($subjectLine) {
$this->subject=$subjectLine;
}
public function setBody($bodyText) {
$this->body=$bodyText;
}
public function setHeaders($sizeHeaders) {
$this->headers=$sizeHeaders;
}
public function setFrom($whoFrom) {
$this->from="From:".$whoFrom."\n".$this->headers;
}
// ACCESSOR METHODS
public function getEmail() {
return $this->email;
}
public function getSubject() {
return $this->subject;
}
public function getBody() {
return $this->body;
}
public function getHeaders() {
return $this->headers;
}
public function getFrom() {
return $this->from;
}
public function sendMail($sendHere) {
if (mail(
$sendHere,
stripslashes($this->getSubject()),
stripslashes($this->getBody()),
$this->getFrom()
)
)
echo("<p>Your request has been sent.</P>");
else
echo("<p>Due to technical difficulties, your request could not be delivered.</p>");
}
}
?>
I can post the PHPMailer source files, but that's practically a whole software package...
But what would cause the form's data to literally be forgotten?? How could I prevent it??? (And limiting file size is not a feasible option.) If it helps, the host is 1and1.com.
when the file is bigger than post_max_size the "POST datas" are erased by PHP
a solution would be to send the file by AJAX before to submit the form. look here to know how to do this :
Upload image with JavaScript from another server via AJAX

Using PHP functions to validate a form

The following code worked perfectly before I put them into functions but I cannot figure out how to get this form to work correctly using the functions I created. I know I need to pass variables and create some proper main logic but I really don't know where to go from here. The end product should look something like this form: guestbookonescript
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Guestbook</title>
<meta charset="ISO-8859-1">
</head>
<?php
function check(){
$userErr = $emailErr = $noteErr = "";
$user = $email = $note = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user"]))
$userErr = "Please fill out a name.";
else
$user = $_POST["user"];
if (empty($_POST["email"]))
$emailErr = "Please fill out an email.";
else
$email = $_POST["email"];
if (empty($_POST["note"]))
$noteErr = "Please give us your comments.";
else
$note= $_POST["note"];
}
}
function display(){
print<<<TABLE_BLOCK
<h2>Please Sign Our Guestbook</h2>
<form method="post" action="mock.php">
<table>
<tr>
<td>Name:</td><td><input type="text" size="34" name="user" value="" /><span class="error"><br> $userErr</span></td>
</tr>
<tr>
<td>Email: </td><td><input type="text" size="34" name="email" value="" /><span class="error"><br> $emailErr</span></td>
</tr>
<tr>
<td valign="top">Comments: </td><td><textarea rows="5" cols="25" name="note"> </textarea><span class="error"><br> $noteErr</span></td>
</tr>
<tr>
<td></td><td></td>
</tr>
<tr>
<td></td><td align="right"><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
TABLE_BLOCK;
}
function result(){
print<<<TABLE_BLOCK
<h2>Your Input:</h2>
<table>
<tr>
<td>Name:</td><td>$user</td>
</tr>
<tr>
<td>Email: </td><td>$email</td>
</tr>
<tr>
<td valgin="top">Comments: </td><td>$note</td>
</tr>
</table>
TABLE_BLOCK;
}
if(isset($_REQUEST['submit']))
check();
else
display();
result();
?>
</body>
What Alon is trying to say is that all of your variables are caught in the local scope, to avoid this, you need tell the offending variables that they belong in the global scope. Technically, you don't need to initialize them first, but it's good practice.
Note, you need to ensure that your variables are in the global scope in each function you're using them in.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Guestbook</title>
<meta charset="ISO-8859-1">
</head>
<?php
$userErr = $emailErr = $noteErr = "";
$user = $email = $note = "";
function check(){
global $user, $email, $note;
global $userErr, $emailErr, $noteErr;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user"]))
$userErr = "Please fill out a name.";
else
$user = $_POST["user"];
if (empty($_POST["email"]))
$emailErr = "Please fill out an email.";
else
$email = $_POST["email"];
if (empty($_POST["note"]))
$noteErr = "Please give us your comments.";
else
$note = $_POST["note"];
}
}
function display(){
global $userErr, $emailErr, $noteErr;
print<<<TABLE_BLOCK
<h2>Please Sign Our Guestbook</h2>
<form method="post" action="/">
<table>
<tr>
<td>Name:</td><td><input type="text" size="34" name="user" value="" /><span class="error"><br> $userErr</span></td>
</tr>
<tr>
<td>Email: </td><td><input type="text" size="34" name="email" value="" /><span class="error"><br> $emailErr</span></td>
</tr>
<tr>
<td valign="top">Comments: </td><td><textarea rows="5" cols="25" name="note"> </textarea><span class="error"><br> $noteErr</span></td>
</tr>
<tr>
<td></td><td></td>
</tr>
<tr>
<td></td><td align="right"><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
TABLE_BLOCK;
}
function result(){
global $user, $email, $note;
print<<<TABLE_BLOCK
<h2>Your Input:</h2>
<table>
<tr>
<td>Name:</td><td>$user</td>
</tr>
<tr>
<td>Email: </td><td>$email</td>
</tr>
<tr>
<td valgin="top">Comments: </td><td>$note</td>
</tr>
</table>
TABLE_BLOCK;
}
if(isset($_REQUEST['submit']))
check();
display();
result();
?>
</body>
You need to define variables that was declared outside the function as global. Put this line at start of your function, after function result(){
global $user,$email,$note;
note that variables declared inside the function scope will be deleted after the function execution. you need to declare $user,$email,$note ouside check() (and just declare them as global inside check())

Invite PHP form Using External Text File

REVISED: I'm trying to process a form, validates it and sends emails to these recipients.
<form>
<input name="name1"> <input email="email1">
<input name="name2"> <input email="email2">
<input name="name3"> <input email="email3">
....
<input type="submit" name="submit">
</form>
What I was trying to do was rather than doing a multiple inputs, I'd use the for loop like so..
<form method=GET action="">
<?php
for($i = 1; $i <= 10; $i++)
{
echo 'First name: <input name="firstname[$i]">';
echo 'Last name:<input name="lastname[$i]">';
echo 'Email: <input name="email[$i]"><br>';
}
?>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
$msg = "a message";
$subject = "a subject";
foreach($_POST['email'] as $email){
mail($email, $subject,$msg,'From: ' . $_POST['sendername'] . "\n\r" );
}
?>
My question is I'm not sure what's the best way to validate these fields. Any pointers would be helpful. I'm not a programmer I'm just a beginner.
EDIT
The answer below is for the OP's original question before his EDIT.
Original question: https://stackoverflow.com/revisions/18454820/1
This line was problematic:
echo '<input type="text" name="firstname[]" size="20" value=".(if (isset($_POST['firstname'][$i])) { print htmlspecialchars($_POST['firstname'][$i]); })." />';
and was replaced by: (to get it working)
echo '<input type="text" name="firstname[]" size="20" />';
Plus, I replaced your form action to action=""
Working code:
<!DOCTYPE html>
<html>
<head>
<title>PHP FORM </title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<?php
// Print some introductory text:
print '<h2>Party Invitation Form</h2>
<p>Please enter list of people with first name, last name and email address to get an invitation by email.</p>';
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$problem = FALSE; // No problems so far.
// Check for each value...
for ($i = 0; $i < count($_POST['email']); $i++) {
if (empty($_POST['firstname'][$i])) {
$problem = TRUE;
echo '<input type="text" name="firstname[]" size="20" />';
}
if (empty($_POST['lastname'][$i])) {
$problem = TRUE;
}
if (empty($_POST['email'][$i]) || (substr_count($_POST['email'][$i], '#') != 1) ) {
$problem = TRUE;
}
}
if (!$problem) { // If there weren't any problems...
// Print a message:
echo '<p><b>Thank you for registering! We will send each one an invitation: <b> </b></p>';
for ($i = 0; $i < count($_POST['email']); $i++) {
echo $_POST['firstname'][$i]." ".$_POST['lastname'][$i]." ".$_POST['email'][$i]." <br/>";
// Send the email:
$body = "Thank you {$_POST['firstname'][$i]} for registering with the blah blah blah blah!";
mail($_POST['email'][$i], 'Party Invitation', $body, 'From: email#example.com');
}
// Clear the posted values:
$_POST = array();
} else { // Forgot a field.
print '<p id="error">* Required field! Please try again. Thank you.</p>';
}
} // End of handle form IF.
// Create the form:
?>
<form action="" method="post">
<table>
<tr>
<td>First name:</td>
<td>Last name:</td>
<td>Email:</td>
</tr>
<?php for ($i = 0; $i < 2; $i++) { ?>
<tr>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<input type="text" name="firstname[]" size="20" value="<?php if (isset($_POST['firstname'][$i])) { print htmlspecialchars($_POST['firstname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<input type="text" name="lastname[]" size="20" value="<?php if (isset($_POST['lastname'] [$i])) { print htmlspecialchars($_POST['lastname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?><input type="text" name="email[]" size="20" value="<?php if (isset($_POST['email'][$i])) { print htmlspecialchars($_POST['email'][$i]); } ?>" />
</td>
</tr>
<?php } ?>
<tr><td><p><input type="submit" class="button" name="submit" value="Register!" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>

Submit and show results in the form in the same page

I've a form in which I want the calculate function to be called and displayed on the same page. If there is an error, it should display in the span tag on the same page.
Here's what I have right now, and I'm running into problems:
index.php [UPDATED]:
<?php
if (isset($_POST['submit'])) {
$bdmm = $_POST['bdmm'];
$sdmm = $_POST['sdmm'];
$strings = array(
$bdmm,
$sdmm,
$lgpm
);
if(!$bdmm){
$error = "Error";
exit();
}
elseif(!$sdmm){
$error = "Error";
exit();
}
//check whether the string is numeric
foreach ($string as $string) {
if (!preg_match("/^-?([0-9])+\.?([0-9])+$/", $string))
{
echo "Invalid entry. Please enter a number.";
}
}
$calc = new Calc();
if (isset($bdmm)) {
$calc->calculateMet($bdmm,$sdmm);
}
}
// Defining the "calc" class
class Calc {
private $vs = 0;
private $nob = 0;
private $tw = 0;
public function calculateMet($b,$s)
{
//code to calculate
//display nbnm in textbox
$nbnm = $nobr;
//display twkg in textbox
$tw = $nob * 25;
$twr = round($tw);
$twkg = $tw;
exit;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Calculator</title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body>
<!-- Begin Wrapper -->
<div id="wrapper">
<div id="column">
<form id="deps" name="deps" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
<?php
if (isset($_REQUEST['error'])){
$err = $_REQUEST['error'];
?>
<div id="er"> <span class="er" > <?php echo $err; ?></span></div>
<?php } ?>
<table class="table">
<tr>
<td class="field head"> </td>
<td class="field cv"><label for="met">Metric</label></td>
<td class="field cv"><label for="eng">English</label></td>
</tr>
<tr>
<td class="field head"><label for="bd">Bore Dia.</label></td>
<td class="field"><input type="text" name="bdmm" id="bdmm" /><label for="bdmm">MM</label></td>
</tr>
<tr>
<td class="field head"><label for="sd">Screen Dia.</label></td>
<td class="field"><input type="text" name="sdmm" id="sdmm" /> <label for="sdmm">MM</label></td>
</tr>
<tr>
<td class="field head"><label for="nbn">No. of Bags needed</label></td>
<td class="field"><input type="text" name="nbnm" id="nbnm" value="<?php echo $nbnm; ?>" /></td>
</tr>
<tr>
<td class="field head"><label for="tw">Total Weight</label></td>
<td class="field"><input type="text" name="twkg" id="twkg" value="<?php echo $twkg; ?>" /> <label for="twkg">KG</label></td>
</tr>
</table>
<input type="submit" id="submit" value="Calculate" />
</form>
</div>
</div>
<!-- End Wrapper -->
</body>
</html>
There are mainly two things I want to show in the form:
1- If there is an error, it should display the error in the span tag -
<?php
if (isset($_REQUEST['error'])){
$err = $_REQUEST['error'];
?>
<div id="er"> <span class="er" > <?php echo $err; ?></span></div>
<?php } ?>
I did this^, but it does not throw any error even if the textbox is blank.
2- I want to show the calculated results in the textboxes in the form itself:
<td class="field"><input type="text" name="nbnm" id="nbnm" value="<?php echo $nbnm; ?>" /></td>
<td class="field"><input type="text" name="twkg" id="twkg" value="<?php echo $twkg; ?>" />
^This is throwing an error: Undefined variable nbnm and twkg
Where am I going wrong?
There are several problems with your code.
First, the variables that are established in the Calc class are not going to be directly accessible by code outside of the class declaration. Your code <?php echo $twkg; ?> is not going to work because of scope - the variable twkg does not exist in the global scope where you are outputting the HTML.
You can access those variables in the Calc class, but you've made them private. You will either have to make a getter method for those variables if they remain private (thus <?php echo $calc->getTwkg(); ?>) OR, make them public and access them using the arrow operator (thus <?php echo $calc->twkg; ?>).
As for the error message, for one, as has been pointed out, the post handling code needs to go above the form rendering code, otherwise the form will be rendered before the lower code has a chance to decide if there's an error or not. Second, I am not sure what the use of $_REQUEST['error'] is all about: set $error to false, check for errors, if there is one, stick the error message in it. Then your if looks like this:
if ($error !== false)
echo '<div id="er"><span class="er"> '.$error.'</span></div>';
Here are some general edits... you've got a lot of confusing stuff in there and I don't know what you're doing, so I just put this together in the way of a collection of tips. I suggest you use more descriptive variable names: instead of $nob and $bdmn, use $bore_diameter_minimum - that way it is easy to see what a variable should contain.
// Defining the "calc" class
class Calc {
private $vs = 0;
public $nob = 0; // note that this is public
private $tw = 0;
public function calculateMet($b,$s) {
// do your calculations here
$this->vs = $b * $s;
// use $this->vs, $this->nob to change the private variables declared above
if ($this->vs < $v)
return false;
// return true if the calculation worked
return true;
}
// use public getters to return variables that are private
public function getVs() {
return $this->vs;
}
}
$calc = new Calc();
$error = false;
if (isset($_POST['submit'])) {
$bdmm = isset($_POST['bdmm']) ? $_POST['bdmm'] : false;
$sdmm = isset($_POST['sdmm']) ? $_POST['sdmm'] : false;
if(
$bdmm == false ||
strlen($bdmm) < 1 ||
preg_match("/^-?([0-9])+\.?([0-9])+$/", $bdmm) == false
){
$error = "Invalid Bore Dia.";
}
if(
$sdmm == false ||
strlen($sdmm) < 1 ||
preg_match("/^-?([0-9])+\.?([0-9])+$/", $bdmm) == false
){
$error = "Invalid Screen Dia.";
}
if ($error !== false) {
$result = $calc->calculateMet($bdmm,$sdmm);
if ($result === false)
$error = 'Calculation failed';
}
}
// output an error message
if ($error !== false)
echo '<div class="error">'.$error.'</div>';
echo 'Private test: '.$calc->getVs();
echo 'Public test: '.$calc->nob;
You need to move the php code on top of the page, because you are accessing variables before even they are created.
You need to put $error somehow into the $_REQUEST (because you try to get it from there and it is not there automatically). You should use $_SESSION['error'] instead of $error = "Error!" and if (isset($_SESSION['error'])){ instead of if (isset($_REQUEST['error'])){ .
Move all the code from the bottom to the top. I haven't studied the code too closely, but it seems the script had no chance to set the variables before they were set.

Categories