form processing a radio button in php - php

I have an rsvp form that I am trying to send the value of a radio button but unsure of the php for it, my code is as follows:
<div class="form-group">
<input type="text" name="name" id="name" size="30" value="" placeholder="Name(s)" class="text-input form-control" />
<label class="error" for="name" id="name_error">Name is required.</label>
</div>
<div class="form-group">
<input type="radio" name="response" id="response_accepted" value="accepted" checked="checked" > Will be there
<input type="radio" name="response" id="response_declined" value="declined"> Won't make it
<label class="error" for="response" id="name_error">Please select an option</label>
</div>
<div class="form-group">
<input type="text" name="guests" id="guests" size="30" value="" placeholder="No. of guests attending" class="text-input form-control" />
<label class="error" for="guests" id="guests_error">No. of guests is required.</label>
</div>
but i'm not sure of the php that collects the value of the radio button but have got the other fields to pass the data using:
<?php
if ((isset($_POST['name'])) && (strlen(trim($_POST['name'])) > 0)) {
$name = stripslashes(strip_tags($_POST['name']));
} else {$name = 'No name entered';}
if ((isset($_POST['guests'])) && (strlen(trim($_POST['guests'])) > 0)) {
$guests = stripslashes(strip_tags($_POST['guests']));
} else {$guests = 'No # of guests entered';}
?>

It will process in the same way as the other, the only difference is that you already know its value, so you will need to
if ((isset($_POST['response'])) && ($_POST['response'] == 'accepted' ) {
$response = 'Accepted';
} else {$response= 'Not Accepted';}

This code will help you
$response = $_POST['response'] ;
if(isset($response) && $resonse == "accepted" )){
echo "Accepted" ;
}
else{ echo "Declined" ; }

Related

Posting multiple checkboxes using PHP and sending to an email

I am fairly new with using PHP. I have a form that I am using to send a contact form form a webpage to an email address.
I am having trouble passing multiple checkboxes styled with a comma. For example, if the user picks checkbox1 and checkbox4, the code will be styled: checkbox1, , , checkbox4. I don't want to display the commas, unless the user picks the checkboxes. Let me know if that makes sense or not.
This is the HTML:
<code>
<form id="contact_form" class="contact" method="post" action="email_process.php">
<input class="firstname text" name="firstname" type="text" placeholder="FIRST NAME:" required>
<input class="lastname text" name="lastname" type="text" placeholder="LAST NAME:" required><br><br>
<input class="email text" name="email" type="email" placeholder="EMAIL:" required>
<input class="name text" name="phone" type="tel" placeholder="PHONE NUMBER:" required><br><br>
<label>Would you like to be contacted by:</label>
<input name="how" class="emailbtn radio" type="checkbox" value="Email">
<label>EMAIL</label>
<input name="how2" class="phonebtn radio" type="checkbox" value="Phone">
<label>PHONE NUMBER</label><br><br>
<div class="one">
<label class="margin">EVENT DATE:</label><br>
<input name="month" class="month small" type="number" placeholder="MM">
<input name="day" class="day small" type="number" placeholder="DD">
<input name="year" class="year small" type="number" placeholder="YYYY">
</div>
<div class="one">
<label class="margin">EVENT LOCATION:</label><br>
<input name="location" class="location text" type="text">
</div>
<label>Services we may assist you with:</label><br><br>
<div class="two">
<input name="services" class="chefbtn radio" type="checkbox" value="Personal Chef">
<label>PERSONAL CHEF</label><br>
<input name="services2" class="cateringbtn radio" type="checkbox" value="Private Cooking Classes">
<label>PRIVATE COOKING CLASSES</label>
</div>
<div class="two">
<input name="services3" class="chefbtn radio" type="checkbox" value="Event Catering">
<label>EVENT CATERING</label><br>
<input name="services4" class="cateringbtn radio" type="checkbox" value="Resteraunt Consulting">
<label>RESTERAUNT CONSULTING</label>
</div>
<input name="heard" class="heard text" type="text" placeholder="HOW DID YOU HEAR ABOUT US?">
<textarea name="comments" class="comments" type="text" placeholder="ADDITIONAL COMMENTS:"></textarea>
<input class="submit" type="image" src="../images/contact/s1_submit_btn.png">
</form>
</code>
This is my PHP:
<code>
<?php
//Prefedined Variables
$to = "Enter email here";
// Email Subject
$subject = "Contact from your website.";
// This IF condition is for improving security and Prevent Direct Access to the Mail Script.
if($_POST) {
// Collect POST data from form
$firstname = stripslashes($_POST['firstname']);
$lastname = stripslashes($_POST['lastname']);
$email = stripslashes($_POST['email']);
$how = stripslashes($_POST['how']);
$how2 = stripslashes($_POST['how2']);
$phone = stripslashes($_POST['phone']);
$month = stripslashes($_POST['month']);
$day = stripslashes($_POST['day']);
$year = stripslashes($_POST['year']);
$location = stripslashes($_POST['location']);
$services = stripslashes($_POST['services']);
$services2 = stripslashes($_POST['services2']);
$services3 = stripslashes($_POST['services3']);
$services4 = stripslashes($_POST['services4']);
$heard = stripslashes($_POST['heard']);
$comments = stripslashes($_POST['comments']);
if ( ! empty($how) && ! empty($how2) ) {
$contact_type = $how.', '.$how2;
} elseif (! empty($how)){
$contact_type = $how;
} elseif (! empty($how2)){
$contact_type = $how2;
}
if ( ! empty($services) || ! empty($services2) || ! empty($services3) || ! empty($services4)) {
$contact_type2 = $services. ', ' .$services2. ', ' .$services3. ', ' .$services4;
}
// Collecting all content in HTML Table
$content='<table width="100%">
<tr><td align "center"><b>Contact Details</b></td></tr>
<tr><td>First Name:</td><td> '.$firstname.'</td></tr>
<tr><td>Last Name:</td><td> '.$lastname.'</td></tr>
<tr><td>Email:</td><td> '.$email.' </td></tr>
<tr><td>Phone:</td> <td> '.$phone.'</td></tr>
<tr><td>How Should We Contact You?</td> <td> '.$contact_type.'</td></tr>
<tr><td>Event Date:</td><td> '.$month.' / '.$day.' / '.$year.' </td></tr>
<tr><td>Location:</td> <td> '.$location.'</td></tr>
<tr><td>Which Services Are You Interested In?</td> <td> '.$contact_type2.'</td></tr>
<tr><td>How Did You Hear About Us?</td> <td> '.$heard.'</td></tr>
<tr><td>Comments:</td> <td> '.$comments.'</td></tr>
<tr><td>Date:</td> <td> '.date('d/m/Y').'</td></tr>
</table> ';
// Define email variables
$headers = "From:".$email."\r\n";
$headers .= "Reply-to:".$email."\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8';
if (! empty($how) || ! empty($how2)) {
if (! empty($services) || ! empty($services2) || ! empty($services3) || ! empty($services4)) {
if( ! empty($firstname) && ! empty($lastname) && ! empty($email) && ! empty($phone) && ! empty($month) && ! empty($day) && ! empty($year) && ! empty($location) && ! empty($heard) && ! empty($comments) ) {
// Sending Email
if( mail($to, $subject, $content, $headers) ) {
print "Thank you, I will get back to you shortly!<br>";
return true;
}
else {
print "An error occured and your message could not be sent.";
return false;
}
}
else {
print "An error occured and your message could not be sent.";
return false;
}
}
}
}
</code>
EDIT:
After some research and the right guidance I came across an answer that helped me solve this. If anyone else is having the same problem feel free to refer to this.
<?php
//Prefedined Variables
$to = "Enter email here";
// Email Subject
$subject = "Contact from your website.";
// This IF condition is for improving security and Prevent Direct Access to the Mail Script.
if($_POST) {
// Collect POST data from form
$firstname = stripslashes($_POST['firstname']);
$lastname = stripslashes($_POST['lastname']);
$email = stripslashes($_POST['email']);
$how = 'None';
if(isset($_POST['how']) && is_array($_POST['how']) && count($_POST['how']) > 0){
$selectedHow = implode(', ', $_POST['how']);
}
$phone = stripslashes($_POST['phone']);
$month = stripslashes($_POST['month']);
$day = stripslashes($_POST['day']);
$year = stripslashes($_POST['year']);
$location = stripslashes($_POST['location']);
$services = 'None';
if(isset($_POST['services']) && is_array($_POST['services']) && count($_POST['services']) > 0){
$selectedServices = implode(', ', $_POST['services']);
}
$heard = stripslashes($_POST['heard']);
$comments = stripslashes($_POST['comments']);
// Collecting all content in HTML Table
$content='<table width="100%">
<tr><td align "center"><b>Contact Details</b></td></tr>
<tr><td>First Name:</td><td> '.$firstname.'</td></tr>
<tr><td>Last Name:</td><td> '.$lastname.'</td></tr>
<tr><td>Email:</td><td> '.$email.' </td></tr>
<tr><td>Phone:</td> <td> '.$phone.'</td></tr>
<tr><td>How Should We Contact You?</td> <td> '.$selectedHow.'</td></tr>
<tr><td>Event Date:</td><td> '.$month.' / '.$day.' / '.$year.' </td></tr>
<tr><td>Location:</td> <td> '.$location.'</td></tr>
<tr><td>Which Services Are You Interested In?</td> <td> '.$selectedServices.'</td></tr>
<tr><td>How Did You Hear About Us?</td> <td> '.$heard.'</td></tr>
<tr><td>Comments:</td> <td> '.$comments.'</td></tr>
<tr><td>Date:</td> <td> '.date('d/m/Y').'</td></tr>
</table> ';
// Define email variables
$headers = "From:".$email."\r\n";
$headers .= "Reply-to:".$email."\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8';
if( ! empty($firstname) && ! empty($lastname) && ! empty($email) && ! empty($phone) && ! empty($selectedHow) && ! empty($month) && ! empty($day) && ! empty($year) && ! empty($location) && ! empty($selectedServices) && ! empty($heard) && ! empty($comments) ) {
// Sending Email
if( mail($to, $subject, $content, $headers) ) {
print "Thank you, I will get back to you shortly!<br>";
return true;
}
else {
print "Please go back and make sure that all fields have been filled out.";
return false;
}
}
else {
print "An error occured and your message could not be sent.";
return false;
}
}
<form id="contact_form" class="contact" method="post" action="email_process.php">
<input class="firstname text" name="firstname" type="text" placeholder="FIRST NAME:" required>
<input class="lastname text" name="lastname" type="text" placeholder="LAST NAME:" required><br><br>
<input class="email text" name="email" type="email" placeholder="EMAIL:" required>
<input class="name text" name="phone" type="tel" placeholder="PHONE NUMBER:" required><br><br>
<label>Would you like to be contacted by:</label>
<input name="how[]" class="emailbtn radio" type="checkbox" value="Email">
<label>EMAIL</label>
<input name="how[]" class="phonebtn radio" type="checkbox" value="Phone">
<label>PHONE NUMBER</label><br><br>
<div class="one">
<label class="margin">EVENT DATE:</label><br>
<input name="month" class="month small" type="number" placeholder="MM">
<input name="day" class="day small" type="number" placeholder="DD">
<input name="year" class="year small" type="number" placeholder="YYYY">
</div>
<div class="one">
<label class="margin">EVENT LOCATION:</label><br>
<input name="location" class="location text" type="text">
</div>
<label>Services we may assist you with:</label><br><br>
<div class="two">
<input name="services[]" class="chefbtn radio" type="checkbox" value="Personal Chef">
<label>PERSONAL CHEF</label><br>
<input name="services[]" class="cateringbtn radio" type="checkbox" value="Private Cooking Classes">
<label>PRIVATE COOKING CLASSES</label>
</div>
<div class="two">
<input name="services[]" class="chefbtn radio" type="checkbox" value="Event Catering">
<label>EVENT CATERING</label><br>
<input name="services[]" class="cateringbtn radio" type="checkbox" value="Resteraunt Consulting">
<label>RESTERAUNT CONSULTING</label>
</div>
<input name="heard" class="heard text" type="text" placeholder="HOW DID YOU HEAR ABOUT US?">
<textarea name="comments" class="comments" type="text" placeholder="ADDITIONAL COMMENTS:"></textarea>
<input class="submit" type="image" src="../images/contact/s1_submit_btn.png">
</form>
You need to have the name of those checkboxes as an array. Like:
<label>Would you like to be contacted by:</label>
<input name="how[]" class="emailbtn radio" type="checkbox" value="Email">
<label>EMAIL</label>
<input name="how[]" class="phonebtn radio" type="checkbox" value="Phone">
<label>PHONE NUMBER</label><br><br>
Do same for services:
<input name="services[]" class="chefbtn radio" type="checkbox" value="Personal Chef">
<label>PERSONAL CHEF</label><br>
<input name="services[]" class="cateringbtn radio" type="checkbox" value="Private Cooking Classes">
<label>PRIVATE COOKING CLASSES</label>
</div>
<div class="two">
<input name="services[]" class="chefbtn radio" type="checkbox" value="Event Catering">
<label>EVENT CATERING</label><br>
<input name="services[]" class="cateringbtn radio" type="checkbox" value="Resteraunt Consulting">
Then in your php:
$how = stripslashes($_POST['how']);
// is actually an array and holds its values in a comma separated format
//no need for how2
//The same approach for services: it's also an array now. if you followed the html above
$services = stripslashes($_POST['services']);
It will also be good if you assign different unique error messages unlike you did along
if( ! empty($firstname) && ! empty($lastname) && ! empty($email) && ! empty($phone) && ! empty($how) && ! empty($month) && ! empty($day) && ! empty($year) && ! empty($location) && ! empty($services) && ! empty($heard) && ! empty($comments) ) {
// Sending Email
if( mail($to, $subject, $content, $headers) ) {
print "Thank you, I will get back to you shortly!<br>";
return true;
}
else {
print "An error occured and your message could not be sent.";//here 1
return false;
}
}
else {
print "An error occured and your message could not be sent.";//here 2
return false;
}
}
You can then find out if it's the outer if( ! empty($firstname) && ... or the mail function that is failing
try it with php method array filter and implode:
<?php
$services[] = "test";
$services[] = "";
$services[] = "test";
$services[] = "";
$arr = array_filter($services, function($elem){
return $elem != "";
});
echo implode(", ", $arr);

Use PHP to enter value from form in to multiple tables in mySQL

Im doing a registration form and I have to enter the information in to 3 tables in mysql. I have tried a few things but cant seem to get it right. This is what I have so far. My registration form looks as follows:
function fix($str){
$str = trim($str);
$str = stripslashes($str);
return $str;
}
if($_POST['submit'])
{
$first = fix($_POST['firstName']);
$last = fix($_POST['lastName']);
$email = fix($_POST['email']);
$userName = fix($_POST['userName']);
$passWord = fix($_POST['passWord']);
$reTyped = fix($_POST['confPassword']);
$secA = $_POST['secA'];
$secQ = $_POST['secQ'];
require_once('user_registration.php');
}
?>
<!DOCTYPE, Head, Body & Nav here>
<div class="account-container register">
<div class="content clearfix">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<h1>New User Registration</h1>
<div class="login-fields">
<div class="field">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" placeholder="First Name" class="login" />
</div> <!-- /field -->
<div class="field">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" placeholder="Last Name" class="login" />
</div> <!-- /field -->
<div class="field">
<label for="userName">User Name:</label>
<input type="text" id="userName" name="userName" placeholder="User Name" class="login" />
</div><!-- /field -->
<div class="field">
<label for="email">Email Address:</label>
<input type="text" id="email" name="email" placeholder="Email" class="login" />
</div> <!-- /field -->
<div class="field">
<label for="passWord">Password:</label>
<input type="password" id="passWord" name="passWord" placeholder="Password" class="login" />
</div> <!-- /field -->
<div class="field">
<label for="confPassword">Confirm Password:</label>
<input type="password" id="confPassword" name="confPassword" placeholder="Confirm Password" class="login" />
</div><!--field-->
<div class="field">
<label for="secQ">Security Question</label>
<select name="secQ" id="secQuestion" placeholder="Security" class="dropdown">
<option value="No Selection"
<?php if(!$_POST || $_POST['secQ'] == 'No Selection')
{ echo 'selected'; }?>>--Select A Security Question--</option>
<option value="0"
<?php if(!$_POST || $_POST['secQ'] == '0')
{ echo 'selected'; }?>>What is your mothers maiden name</option>
<option value="1"
<?php if(!$_POST || $_POST['secQ'] == '1')
{ echo 'selected'; }?>>In what city were you born</option>
<option value="2"
<?php if(!$_POST || $_POST['secQ'] == '2')
{ echo 'selected'; }?>>What is your favorite color</option>
<option value="3"
<?php if(!$_POST || $_POST['secQ'] == '3')
{ echo 'selected'; }?>>What year did you graduate HighSchool</option>
<option value="4"
<?php if(!$_POST || $_POST['secQ'] == '4')
{ echo 'selected'; }?>>What is the name of your first boy/girl friend</option>
<option value="5"
<?php if(!$_POST || $_POST['secQ'] == '5')
{ echo 'selected'; }?>>What was the name of your first pet</option>
<option value="6"
<?php if(!$_POST || $_POST['secQ'] == '6')
{ echo 'selected'; }?>>What street did you grow up on</option>
</select>
</div>
<div class="field">
<label for="secA">Security Answer</label>
<input type="text" id="secA" name="secA" placeholder="Answer" class="login" />
</div>
</div> <!-- /login-fields -->
<div class="login-actions">
<span class="login-checkbox">
<input id="Field" name="terms" type="checkbox" class="field login-checkbox" value="First Choice" tabindex="4" />
<label class="choice" for="Field">Agree with the Terms & Conditions.</label>
</span>
<input type="submit" id="register" name="submit" class="button btn btn-primary btn-large" value="Register" />
</div> <!-- .actions -->
</form>
</div> <!-- /content -->
Then the PHP page I have attached to the form as noted in the first "if" statement is the following - user_registration.php:
<?php
require_once('includes/checkPassword.php');
$usernameMinChars = 6;
$errors = array();
if (strlen($userName) < $usernameMinChars)
{
$errors[] = "Username must be at least $usernameMinChars characters.";
}
if (preg_match('/\s/', $userName))
{
$errors[] = 'Username should not contain spaces.';
}
$checkPwd = new CheckPassword($passWord);
$checkPwd->requireMixedCase();
$passwordOK = $checkPwd->check();
if (!$passwordOK) {
$errors[] = array_merge($errors, $checkPwd->getErrors());
}
if ($passWord != $reTyped) {
$errors[] = "Your passwords don't match.";
}
if (!$errors) {
//include connection file
require('includes/usrConnect.php');
$conn = dbConnect('write');
//create salt using current timestamp
$salt = SALT .time();
//encrypt pwd with salt
$hashword = sha1($passWord . $salt);
//prepare sql statement
$sql = "INSERT INTO User (User_Name) VALUES('$userName')";
$sql .= "INSERT INTO User_Parameter (User_Identity, User_Password, User_Salt) VALUES('$User_Identity', '$hashword', '$salt')";
$sql .= "INSERT INTO User_Profile (User_Identity, Profile_FirstName, Profile_LastName, Profile_Email, Profile_Question, Profile_Answer)
VALUES('$User_Identity', '$first', '$last', '$email', '$secQ', '$secA')";
if($stmt = $conn->query($sql))
{
$User_Identity = $stmt->insert_id;
do{
if($result = $conn->affected_rows())
{
while ($result > 0)
{
$success = 'User successfully created '.$User_Identity;
header('Location: login.php');
}
} $result->free();
}while($conn->next_result());
}
elseif($stmt->errno == 1062)
{
$errors[] = "$userName already exists, Please select another username.";
}else{
$errors[] = 'Sorry, there was a problem processing your request.';
}
}
?>
The problem is that I have 3 tables to insert the information in to. User(for the user_name), User_Parameter(for the password & salt), & User_Profile(for the name, email, & security question / answer).
I just cant figure out how to do the queries correctly. I have tried it this way and I have also tried naming each query something different and can't get it nested correctly in order to correctly get the User_Identity from the first insert in order to input the information in the other queries. Can anyone help?
I think you must execute these 3 queries separately, it actually will work.
$conn->query("INSERT INTO User (User_Name) VALUES('$userName')");
$conn->query("INSERT INTO User_Parameter (User_Identity, User_Password, User_Salt) VALUES('$User_Identity', '$hashword', '$salt')");
$stmt = $conn->query("INSERT INTO User_Profile (User_Identity, Profile_FirstName, Profile_LastName, Profile_Email, Profile_Question, Profile_Answer) VALUES('$User_Identity', '$first', '$last', '$email', '$secQ', '$secA')");
if ($stmt) {
// then your code goes
}
I think just complete this three tables into one.
and using one insert query

PHP - Form error handling issue

I am trying to create error messages if certain conditions aren't met. So the user fills out a form and if a field is empty or doesn't pass my validation it returns the error message.
This is the form:
if (isset($_POST)) {
if (checkEmail($email) == TRUE && $name != NULL && $surName != NULL) {
mysql_query( "INSERT INTO USR_INFO (NAME, MAIL, SURNAME)
VALUES ('$name', '$email','$surName') ") or die(mysql_error());
header('Location: thanks.php');
}
else {
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">First Name</label>
<input type="text" name="name" id="name" value="' .$_POST['name'].'" />
<span class="required">*</span>
<label for="surName">Last Name</label>
<input type="text" name="surName" id="surName" value="' .$_POST['surName']. '" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="' .$_POST['email']. '" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
} else {
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">First Name</label>
<input type="text" name="name" id="name" value="" />
<span class="required">*</span>
<label for="surName">Last Name</label>
<input type="text" name="surName" id="surName" value="" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
So what I tried is adding an array to display the error messages like so:
$errorMessage = array();
And add this to the html form field with the proper message:
$error[] = "Error Message";
Now what I am stuck with is that I want to have the error show only if a user doesn't meet the conditions
if ($name == NULL) {$error[] = "Error Message";}
if ($surName == NULL) {$error[] = "Error Message 2";}
if (checkEmail($email) == FALSE || NULL) {$error[] = "Error Message 3";}
But I can't make it work. When I tried to implement this logic it will parse the page fine and the validation works as well but the error messages wont show up if I leave a required field blank. My guess is that I didn't loop through it properly.
Help is much appreciated!
EDIT:
I tried the answer that was posted by Frosty Z and this is what I have at the moment:
if (isset($_POST)) {
$errorMessage = array();
if ($name == '') { $errors[] = "Input name please." }
if ($surName == '') { $errors[] = "Input last name please." }
if (!checkEmail($email)) { $errors[] = "Email address not valid." }
if (count($error) == 0) {
mysql_query( "INSERT INTO USR_INFO (NAME, MAIL, SURNAME)
VALUES ('$name', '$email', '$surName') ") or die(mysql_error());
header('Location: thanks.php');
exit;
else {
if (count($errors) > 0)
echo "<p>Sorry, there are problems with the information you have provided:</p>";
foreach($errors as $error)
echo '<p class="error">'.$error.'</p>';
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="' .$_POST['name'].'" />
<span class="required">*</span>
<label for="surName">Last name</label>
<input type="text" name="surName" id="surName" value="' .$_POST['surName']. '" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="' .$_POST['email']. '" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
} else {
echo'<form action="<?php echo $_SERVER[\'PHP_SELF\']; ?>" method="POST">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="" />
<span class="required">*</span>
<label for="surName">Achternaam</label>
<input type="text" name="surName" id="surName" value="" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';
}
With this my page won't be parsed. I have error reporting on but it doesn't show anything besides a
Internal server error 500
in my console log(Firebug)
Here is some rewriting of your work with a minimal handling of error messages.
BTW, you should consider adopting a decent PHP framework which will help you to handle a lot of common development tasks.
$name = '';
$surName = '';
$email = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['name'];
$surName = $_POST['surName'];
$email = $_POST['email'];
$errors = array();
if ($name == '') { $errors[] = "Please type your name."; }
if ($surName == '') { $errors[] = "Please type your surname."; }
if (!checkEmail($email)) { $errors[] = "Wrong email format."; }
if (count($errors) == 0) {
// tip: use PDO or mysqli functions instead of mysql ones to bind variables.
// currently there is a risk of SQL injection here
mysql_query("INSERT INTO USR_INFO (NAME, MAIL, SURNAME)
VALUES ('$name', '$email','$surName') ") or die(mysql_error());
header('Location: thanks.php');
exit;
}
}
if (count($errors) > 0)
echo '<p>Sorry, there are problems with the information you have provided:</p>';
foreach($errors as $error)
echo '<p class="error">'.$error.'</p>';
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">
<label for="name">First Name</label>
<input type="text" name="name" id="name" value="'.htmlspecialchars($name).'" />
<span class="required">*</span>
<label for="surName">Last Name</label>
<input type="text" name="surName" id="surName" value="'.htmlspecialchars($surName).'" />
<span class="required">*</span>
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#domain.com" value="'.htmlspecialchars($email).'" />
<span class="required">*</span>
<input type="submit" name="submit" id="submit">
</form>';

Code doesn't execute until button triggered

I need your help. So the problem is that I've done some coding but I don't know why it doesn't work when page loads. But when I trigger any button (Save Info Modification Or Cancel Info Modification) it works.
php code :
if(isset($_POST['nametb']) && isset($_POST['usernametb']) && isset($_POST['emailtb']) && isset($_POST['confirmtb']) && isset($_POST['abouttb']) && isset($_POST['interesttb']) && isset($_POST['dreamtb']) && isset($_POST['liketb']) && isset($_POST['schooltb']) && isset($_POST['schoolyrtb']) && isset($_POST['occupationtb']) && isset($_POST['occupationyrtb'])){
$select_info = "SELECT * from user_info WHERE id='$user_id'";
if($select_info_run = #mysql_query($select_info)){
$namedb = mysql_result($select_info_run, 0, 'name');
$usernamedb = mysql_result($select_info_run, 0, 'username');
$emaildb = mysql_result($select_info_run, 0, 'email');
$confirmdb = mysql_result($select_info_run, 0, 'email');
$aboutdb = mysql_result($select_info_run, 0, 'about');
$interestdb = mysql_result($select_info_run, 0, 'interest');
$dreamdb = mysql_result($select_info_run, 0, 'dream');
$likedb = mysql_result($select_info_run, 0, 'like');
$schooldb = mysql_result($select_info_run, 0, 'school');
$schoolyrdb = mysql_result($select_info_run, 0, 'schoolyr');
$occupationdb = mysql_result($select_info_run, 0, 'occupation');
$occupationyrdb = mysql_result($select_info_run, 0, 'occupationyr');
}
else{
echo 'Server down :(';
}
}
else{
echo server down :(';
}
html code :
<form action="<?php if(isset($current_file)){ echo $current_file; } ?>" method="POST">
<fieldset id="fieldset1">
<legend style="font-family: Ubuntu; font-size:20px;">Info</legend>
<label id="name" title="Name" for="textbox1">Name :</label>
<label id="username" title="UserName" for="textbox2">UserName :</label>
<label id="email" title="Email" for="textbox3">Email :</label>
<label id="confirm" title="Confirm Email" for="textbox4">Confirm :</label>
<br />
<input type="text" id="textbox1" name="nametb" value="<?php if(isset($namedb)){ echo $namedb; } ?>" />
<input type="text" id="textbox2" name="usernametb" value="<?php if(isset($usernamedb)){ echo $usernamedb; } ?>" />
<input type="text" id="textbox3" name="emailtb" value="<?php if(isset($emaildb)){ echo $emaildb; } ?>" />
<input type="text" id="textbox4" name="confirmtb" value="<?php if(isset($confirmdb)){ echo $confirmdb; } ?>" />
<br /><br />
<div id="hrln"><hr /></div>
<label id="about" title="About you" for="textarea1">About :</label>
<label id="interest" title="You are interested in?" for="textarea2">Interested in :</label>
<br />
<textarea id="textarea1" name="abouttb"><?php if(isset($aboutdb)){ echo $aboutdb; } ?></textarea>
<textarea id="textarea2" name="interesttb"><?php if(isset($interestdb)){ echo $interestdb; } ?></textarea>
<br /><br /><br /><br /><br /><hr />
<label id="dream" title="Your Dream?" for="textarea3">Dream :</label>
<label id="like" title="What do you like?" for="textarea4">You like :</label>
<br />
<textarea id="textarea3" name="dreamtb"><?php if(isset($dreamdb)){ echo $dreamdb; } ?></textarea>
<textarea id="textarea4" name="liketb"><?php if(isset($likedb)){ echo $likedb; } ?></textarea>
<br /><br /><br /><br /><br /><hr />
<label id="education" title="Your school" for="textbox5">School | University :</label>
<label id="educationyr" title="Year" for="textbox6">Year :</label>
<br />
<input type="text" name="schooltb" id="textbox5" value="<?php if(isset($schooldb)){ echo $schooldb; } ?>" />
<input type="text" name="schoolyrtb" id="textbox6" value="<?php if(isset($schoolyrdb)){ echo $schoolyrdb; } ?>" />
<br /><br /><hr />
<label id="occupation" title="Occupation" for="textbox7">Occupation :</label>
<label id="occupationyr" title="Year" for="textbox6">Year :</label>
<br />
<input type="text" id="textbox7" name="occupationtb" value="<?php if(isset($occupationdb)){ echo $occupationdb; } ?>" />
<input type="text" id="textbox8" name="occupationyrtb" value="<?php if(isset($occupationyrdb)){ echo $occupationyrdb; } ?>" />
<br /><br /><hr />
<label id="passwords" title="For Security Purpose" for="textbox9">Password :</label>
<input type="password" id="textbox9" name="passwordstb" />
<input type="submit" value="Save Info Modification" name="save" id="button1" />
<input type="submit" value="Cancel Info Modification" name="cancel" id="button2" />
</fieldset>
</form>
Do you want the form to display? Then, get rid of that echo in the last "else". Then the form will display. When a user clicks the submit button, the form will post that information to the page.
Also, your 2nd "else{ echo server down :('; }" is missing a quote before 'server down :(';
The key to your problems is what I call "isolation": you need to isolate what is causing the issue. I recommend the "comment-out-code-and-refresh-page" technique if you're pressed for time. But it's far better to analyze and interpret your code and UNDERSTAND why it's not doing what you want.
It runs when you click the buttons because of this:
if(isset($_POST['nametb']) && isset($_POST['usernametb']) && isset($_POST['emailtb']) &&
isset($_POST['confirmtb']) && isset($_POST['abouttb']) && isset($_POST['interesttb']) &&
isset($_POST['dreamtb']) && isset($_POST['liketb']) && isset($_POST['schooltb']) &&
isset($_POST['schoolyrtb']) && isset($_POST['occupationtb']) &&
isset($_POST['occupationyrtb'])){
Your if statement is checking if anything in the POST array is set before doing anything.
This is sent by the form when you click a submit button (which is either button, it seems).
If you are trying to populate the fields on page load, you need to move your SELECT statement an related code outside of that if statement. Since it seems you would be using this form to update database data, you should put your INSERT/UPDATE statements inside the if statement so that they won't run until you click the submit button (pending other logical operations to take into account WHICH button was pressed.).

2 options, PHP to ignore details of second if first is selected and vice versa

I'm having some trouble with some PHP.
Here's a shortened version of the HTML:
<label for="yes_or_no">would you like to tell me your favourite colours?</label>
<input type="radio" name="yes_or_no" id="yes" value="yes" />
<label for="yes">yes</label>
<input type="radio" name="yes_or_no" id="no" value="no" />
<label for="no">no</label>
<div id="colours_box">
<label for="colours">great! please select from the following list:</label>
<input type="checkbox" name="colours[]" id="blue" value="blue" />
<label for="blue">blue</label>
<input type="checkbox" name="colours[]" id="yellow" value="yellow" />
<label for="yellow">yellow</label>
<input type="checkbox" name="colours[]" id="red" value="red" />
<label for="red">red</label>
<input type="checkbox" name="colours[]" id="green" value="green" />
<label for="green">green</label>
<input type="checkbox" name="colours[]" id="other_colour" value="other_colour" />
<label for="other_colour">other_colour</label>
<div id="other_colour_box">
<textarea name="other_colour_detail" id="other_colour_detail"></textarea>
</div>
</div>
The colours_box DIV is hidden and appears when #no is selected and disappears when #yes is selected using some basic JavaScript. The other_colour_box DIV does a similar thing- it's hidden by default and when #other_colour is checked it appears, when it's unchecked it disappears.
What I'd like it to do is this:
if 'yes' is selected in the first instance, all the checkboxes and textarea are ignored, even if they selected 'no' first and entered details to the checkboxes and textarea.
if the other_colour_detail textarea has been written in but 'other_colour' has subsequently been unchecked, nothing is returned for the 'other_colour_detail' textarea
Here's the PHP:
$yes_or_no = $_POST['yes_or_no'] ;
$colours = $_POST['colours'] ;
$other_colour_detail = $_POST['other_colour_detail'] ;
$colours_to_email .= implode("\n\t", $colours) ;
if (($yes_or_no == 'no') && ($colours != "")) {
$colours_to_email ;
}
if (($yes_or_no == 'no') && ($other_colour != "") && ($other_colour_detail != "")) {
$details_of_other_colour = ":\n\t$other_colour_detail" ;
}
This would then feed back to me via email something like this:
"Did they want to tell me which colours they preferred?\n" .
"$yes_or_no-\t" . "$colours_to_email" .
"$details_of_other_colour" ;
Thanks for having a look,
Martin.
You should disable the colours[] elements when "No" is checked. Disabled elements are not submitted:
<script type="text/javascript">
function toggle_colour_inputs(enabled) {
if ( "yes" ) {
document.form1.colours.disabled=false;
}
else {
document.form1.colours.disabled=true;
}
}
</script>
<input type="radio" name="yes_or_no" id="yes" value="yes" onchange="toggle_colour_inputs(this.value)" />
<label for="yes">yes</label>
<input type="radio" name="yes_or_no" id="no" value="no" onchange="toggle_colour_inputs(this.value)" />
<label for="no">no</label>
<?php
$yes_or_no = $_POST['yes_or_no'] ;
$colours = $_POST['colours'] ;
$other_colour_detail = $_POST['other_colour_detail'] ;
$colours_to_email .= implode("\n\t", $colours) ;
if ($yes_or_no == 'no') {
if (count($colours) > 0) {
// colours to email
}
} else {
if (($other_colour != '') && ($other_colour_detail != '')) {
// details of other colour
}
}
?>

Categories