I've spent hours searching SO for this, but I wasn't able to find anyone who was trying to do what I was.
I'm trying to use http.post to send (an array of) data from an HTML form through Angular to PHP. When I try to do this, it sends the hardcoded values in the PHP file to PostgreSQL fine, but I'm not sure if Angular is sending the data to PHP or if I'm not accessing the $_POST variable correctly.
This is the code I have for this right now:
register-form.component.html:
<div class="container">
<h1>Sign Up</h1>
<h5>Items marked with a * are required.</h5> <br>
<form (ngSubmit)="onSubmit(model)" #registerForm="ngForm">
<div class="form-group">
<label for="username">Username *</label>
<input type="text" class="form-control width" id="username" required [(ngModel)]="model.username" name="account[username]"
#username = "ngModel">
<div [hidden]="username.valid || username.untouched" class="alert alert-danger">
Username is required
</div>
</div>
<div class="form-group">
<label for="password">Password *</label>
<input type="text" class="form-control width" id="password" minlength="6" required [(ngModel)]="model.password"
name="account[password]" #password = "ngModel">
<div [hidden]="password.valid || password.untouched" class="alert alert-danger">
Password is required and must be at least 6 characters
</div>
</div>
<div class="form-group">
<label for="email">E-mail *</label>
<input type="text" class="form-control width" id="email" required [(ngModel)]="model.email" name="account[email]"
#email = "ngModel" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$">
<div [hidden]="!email.hasError('pattern') || email.untouched" class="alert alert-danger">
E-mail is required and must be a valid e-mail
</div>
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<input type="text" pattern="[0-9]*" class="form-control width" minlength="10" maxlength="10" id="phoneNumber"
name="account[phone]" [(ngModel)]="model.phoneNumber" #number = "ngModel">
<div [hidden]="number.pristine">
<div [hidden]="!number.hasError('minlength')" class="alert alert-danger">Phone number should only have 10 digits in xxxxxxxxxx format.</div>
<div [hidden]="!number.hasError('pattern')" class="alert alert-danger">Phone number should only have digits.</div>
</div>
</div>
<input type="submit" class="btn btn-success"[disabled]="!registerForm.form.valid" value="Submit">
</form>
</div>
register-form.component.ts:
import { Component, OnInit } from '#angular/core';
import { user } from '../user';
import { Http, HttpModule, Response } from '#angular/http';
import { HttpClient } from '#angular/common/http';
#Component({
selector: 'app-register-form',
templateUrl: './register-form.component.html',
styleUrls: ['./register-form.component.css']
})
export class RegisterFormComponent implements OnInit {
constructor(private http: Http) { }
model = new user('','','','');
ngOnInit() { }
submitted = false;
onSubmit(...event: user[]) {
this.submitted = true;
console.log(event); //just for testing - outputs inputted data from form into console
console.log(event[0]); //same as above
var test = this.http.post('http://localhost/register-form-component.php', event[0]); //should this just be 'event'?
test.subscribe();
}
}
register-form-component.php:
<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=sample user=sample password=sample");
if(!$dbconn) {
echo "connection failed";
exit;
}
$test = ["testuser","testpass132","example#gmail.com",1234566543];
$values = [$_POST['username'], $_POST['password'], $_POST['email'], $_POST['phoneNumber']];
$result = pg_prepare($dbconn, "insert_accounts", 'INSERT INTO accounts (username, password, email, phone_number) VALUES ($1,$2,$3,$4)');
$result = pg_execute($dbconn, "insert_accounts", $test); //this works
$result = pg_execute($dbconn, "insert_accounts", $values); //the data table in PGAdmin skips a primary key every time this file runs; it is because of this line (see edit below).
if (!$result) {
echo "An INSERT query error occurred.\n";
exit;
}
pg_close($dbconn);
?>
Thanks!
EDIT: This wasn't showing up before, but when I open up localhost/register-form-component.php, it gives the following output:
Array
Warning: pg_execute(): Query failed: ERROR: null value in column "username" violates not-null constraint DETAIL: Failing row contains (31, null, null, null, null). in /Library/WebServer/Documents/register-form-component.php on line 16
An INSERT query error occurred.
I assume this means that $_POST contains [null, null, null, null].
This same error shows up when event[0] is changed to event in the http.post().
EDIT 2:
First output is of console.log(event), second is of console.log(event[0])
EDIT 3:
This is what shows up in the network tag after submitting the form
EDIT 4:
In the header tab under network, it shows this.
It turns out that the reason why PHP was showing $_POST as containing null values is because it was empty, as I had not declared what was to be in it. Using the method in Mike Brant's answer, I added the following lines to my code:
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$username = $request->username;
$password = $request->password;
$email = $request->email;
$phoneNumber = $request->phoneNumber;
And it worked! Thank you Jaime for patiently abiding by all of my questions.
Related
I am struggling to find out why it's able to send some data but not others. It submits 'email' and 'password' and 'id'... and just doesn't post 'sex' and 'dob'... I've been staring at it for the past several days.
function doPost(e){ //this doPost(e) function on my app script app is able to allow interaction between my php and my app script app
var error = null;
if(typeof e.parameter.action == 'undefined'){
error = "action parameter required";
}
else if(e.parameter.action == "CRUD"){ //CREATE RECORD PROCCESS - the updateRecord() function is able to create record on a row with corresponding email.
var result = updateRecord(e.parameter.email.trim(), e.parameter.password.trim(), e.parameter.id.trim(), e.parameter.sex.trim(), e.parameter.date.trim(), e.parameter.dob.trim());
}
following is the function which is called by doPost(e) on my app script, and then proceeds to do Update or Create new record if an email does not exist... by basically appending to the spreadsheet.
function updateRecord(email, password, id, sex, date, dob) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var mySheet = sheet.getSheetByName("profiledata");
var lastRow = mySheet.getLastRow();
var ar = [email,password,id,sex,date,dob];
var newRecord = [email,password,id,sex,date,dob];
var range = mySheet.getRange(2, 1, lastRow - 1);
var check = range.createTextFinder(email).findNext(); // this line of code checks the row and gets data by email
var status;
if (check) {
check.offset(0, 0, 1, ar.length).setValues([ar]);
// status = 'Record Updated';
return {
status: "success",
message: "Record Updated"
}
}
else {
range.offset(lastRow - 1, 0, 1, ar.length).setValues([newRecord]);
// status = 'New Record created';
return {
status: "success",
message: "New Record created"
}
}
}
Following is my PHP insert file... post.php... which is able to send form data toward the above doPost(e) function, which in turn runs updateRecord() function
$url = "App script URL "; //this is where I pasted the URL of my app script
$postData = [
"action" => "CRUD",
"email" => $_POST['email'],
"password" => $_POST['password'],
"id" => $_POST['id'], // "ignore this Comment!!" I create an id separately and echo it into the html form input as readonly.
"sex" => $_POST['sex'],
"date" => $_POST['date'],
"dob" => $_POST['dob'],
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $postData
]);
$result = curl_exec($ch);
$result = json_decode($result, 1);
if($result['status'] == "success"){
$returnmsg = $result['message'];
$_SESSION['success'] = $returnmsg;
header("location: table.php?=success $returnmsg");
}else{
$_SESSION['error'] = $result['message'];
$errormsg = $result['message'];
header("location: table.php?=err$errormsg");
}
Below is my HTML form
<form method="post" action="post.php">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="text" name="email" class="form-control" placeholder="Enter email" autocomplete="on">
</div>
<div class="form-group">
<label for="password">password Field</label>
<input type="password" name="password" class="form-control" placeholder="this is a place for password" autocomplete="on">
</div>
<div class="form-group">
<label for="id">id Field</label>
<input type="text" name="id" class="form-control" value="<?php echo $id;?>" readonly>
</div>
<div class="form-group">
<label for="sex"> Gender Field</label>
<input type="text" name="sex" class="form-control" placeholder="this is a place for gender" autocomplete="on">
</div>
<div class="form-group">
<label for="dob">Date of Birth Field</label>
<input type="text" name="dob" class="form-control" placeholder="this is a place for DOB" autocomplete="on">
</div>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
my problem is that this process is only able to send data to the spreadsheet but only up to 'id'... it doesn't submit 'sex' and 'date'
I searched all over google's documentation, and other places, I am coming up with nothing...
This is a question I have seen asked before but I have been unable to find an answer for the newer version of Codeigniter.
Controller
<?php
namespace App\Controllers;
class SendEmail extends BaseController
{
public function index($validation = NULL){
// Load form helper
helper('form');
// Instantiate session
$session = \Config\Services::session();
// Set css, javascript, and flashdata
$data = [
'css' => array('contact.css'),
'js' => array('contact.js'),
'validation' => $validation,
'success' => $session->get('success')
];
// Show views
echo view('templates/header', $data);
echo view('contact', $data);
echo view('templates/footer', $data);
}
public function sendEmail(){
// Instantiate request
$request = $this->request;
// Captcha API
$captchaUser = $request->getPost('g-recaptcha-response');
// Captcha Key loaded from a file left out of the repo
$captchaConfig = config('Config\\Credentials');
$captchaKey = $captchaConfig->captchaKey;
$captchaOptions = [
'secret' => $captchaKey,
'response' => $captchaUser
];
$client = \Config\Services::curlrequest();
$captchaResponse = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', ['form_params' => $captchaOptions]);
$captchaObj = json_decode($captchaResponse->getBody());
// Load validation library
$validation = \Config\Services::validation();
// Set validation rules
$validation->setRules([
'name' => 'required|alpha_dash|alpha_space',
'email' => 'required|valid_email',
'subject' => 'required|alpha_numeric_punct',
'message' => 'required|alpha_numeric_punct'
]);
// Validate inputs
if (!$this->validate($validation->getRules())){
// Run index function to show the contact page again
$this->index($this->validator);
}
// Validate captcha
elseif(!$validation->check($captchaObj->success, 'required')){
$validation->setError('captcha','Did not pass captcha. Please try again.');
$this->index($validation->getErrors());
}
else{
// Set variables to input
$name = $request->getPost('name');
$email = $request->getPost('email');
$subject = $request->getPost('subject');
$message = $request->getPost('message');
// Load email class
$emailC = \Config\Services::email();
// Set email settings
$emailC->setFrom('bensirpent07#benkuhman.com', $name);
$emailC->setReplyTo($email);
$emailC->setTo('benkuhman#gmail.com');
$emailC->setSubject($subject);
$emailC->setMessage($message);
// Testing section
echo '<br>'.$name.'<br>'.$email.'<br>'.$subject.'<br>'.$message;
/* Temporarily disabled for testing purposes
// Send email
if($emailC->send(false)){
// Redirect
return redirect()->to(base_url().'/contact')->with('success', true);
}else{
// Display error
throw new \CodeIgniter\Database\Exceptions\DatabaseException();
};
*/
}
}
}
Contact View
<div class="container">
<div class="row">
<div class="col">
<div class="alert alert-success align-center" id="message-alert" <?php if($success){echo 'style="display:block"';} ?>>Message successfully sent!</div>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<?php echo form_open('send_email', ['id'=>'contactForm'])?>
<div class="form-group">
<label for="name">Name</label>
<input name="name" type="text" class="form-control" id="name" aria-describedby="name" placeholder="Name" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('name')){echo $validation->getError('name');}?></p>
</div>
<div class="form-group">
<label for="email">E-Mail</label>
<input name="email" type="email" class="form-control" id="email" aria-describedby="email" placeholder="E-mail" required>
<small id="emailHelp" class="form-text">I'll never share your email with anyone else.</small>
<?php //echo $validation->email;?>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('email')){echo $validation->getError('email');}?></p>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input name="subject" type="text" class="form-control" id="subject" placeholder="Subject" required>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('subject')){echo $validation->getError('subject');}?></p>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" rows="5" class="form-control" id="message" placeholder="Type your message here." required></textarea>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('message')){echo $validation->getError('message');}?></p>
</div>
<button id="submitButton" type="submit" class="btn btn-primary g-recaptcha" data-sitekey="6Ldf07AZAAAAAAflQCaJcWgGFCWevCswpIrm0mJN" data-callback='onSubmit' data-action='submit'>Submit</button>
<p class="invalid"><?php if(isset($validation)&&$validation->hasError('captcha')){echo $validation->getError('captcha');}?></p>
<?php echo form_close()?>
</div>
</div>
</div>
<script>
function onSubmit(token) {
document.getElementById("contactForm").submit();
}
</script>
<script src="https://www.google.com/recaptcha/api.js"></script>
From my understanding of the way validation used to work in CodeIgniter, is that when you loaded your view after a form validation it would update the values with what was previously entered. This does not seem to be the case for CodeIgniter 4. I've also tried directly loading the views rather than calling the index function on validation fail. Still would not fill in the form values.
Now I could just pass these values to the index function via $data array. Which is the fix I'm going to use for now. This is more so a sanity check to see if there is something basic I'm missing or if I'm incorrectly using the validation format for CodeIgniter 4.
in CI4 you can use old() function to preserve the input value upon form validation:
View file:
<input type="tel" name="phone" value="<?= old('phone'); ?>">
In Controller you must use withInput() in the redirect() code:
$validation = \Config\Services::validation();
$request = \Config\Services::request();
// your input validation rules
$validation->setRules(...)
if($request->getMethod() == "post" && ! $validation->withRequest($request)->run()) {
return redirect()->back()->withInput()->with('error', $this->validation->getErrors());
} else {
// form validation success
}
I am working on a project and trying to create a generic section to save all kinds of form data to the database. I wrote down the following code to send all the data to php field and hence send it to the database. But the issue is, its giving me an error.
if(isset($_POST['data_for']) && $_POST['data_for']=='save') {
$data = $_POST['formdata'];
print_r($data); // This is showing proper array as an output
foreach ($data as $key => $value) {
echo $value['name']; //This gives the key (index value) of the form "Eg. email"
echo $value['value']; //This gives the value of the user input "eg. abc#xyz.com"
$$value['name'] = $value['value']; //This line gives error as "Array to string conversion"
}
echo $email; //This is just a test to print a variable created in runtime
//The insertion to database code goes here.
}
The above code is getting values from the below jquery
$(document).on('submit','form.cat1', function(e){
e.preventDefault();
var forum = $(this).attr('forum');
var method = $(this).attr('method');
var nonce = $(this).attr('nonce');
var data_for = $(this).attr('data-for');
var formdata = $(this).serializeArray();
//alert(formdata);
$.ajax({
url:'formSubmitPoint.php',
method:method,
data:{formdata:formdata, nonce:nonce, forum:forum, data_for:data_for},
//processData: false,
//contentType: false,
success:function(data){
console.log(data);
if (data['result']=='success') {
if (data['action']=='redirect') {
window.location.href=data['location'];
}
if (data['action']=='show') {
$(data['location']).html(data['message']);
}
}
if (data['result']=='error') {
if (data['action']=='show') {
$(data['location']).html(data['message']);
}
}
},
error:function(data){
console.log(data);
}
});
})
And the jquery pulls data from the below html
<form class="was-validated cat1" method="post" forum='feedback' data-for="save" nonce="{$nonce}">
<div class="form-group">
<label for="newPass">Name</label>
<input type="text" class="form-control" id="name" placeholder="Your Name" name="name" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="form-group">
<label for="newPass">Email</label>
<input type="email" class="form-control" id="email" placeholder="Your Email Address" name="email" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="form-group">
<label for="newPass">Contact Number</label>
<input type="number" class="form-control" id="contact" placeholder="Your contact number" name="contact" required>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<div class="form-group">
<label for="newPass">Message</label>
<textarea class="form-control" id="message" name="message" required></textarea>
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
<button type="submit" name="submit" class="btn btn-primary btn-sm">Submit</button>
</form>
$$value['name'] Will give me $email when the value of $value['name']
will be email
There is no possible way of doing that. You can store it's value, or a reference to that object by doing
$email = $value['value']; //this is a copied object
$email = &$value['value']; //this is a reference
EDIT
You can do
foreach ($data as $key => $value) {
echo $value['name'];
echo $value['value'];
$text = $value['name'];
$$text = $value['value'];
echo $email;
}
You can't create a Variable Variable from an array, because you would convert an array into a string. You must create a string type variable to help it.
foreach ($data as $key => $value) {
$text = $key;
$$text = $value;
echo $email;
}
So i have made an SignUP form in AngularJS+PHP+MySQL and now i want to catch PDO exception in my angular so I can make an IF duplicate entry for example 'login' I can print it out in my Angular, but i have no idea where to begin. I have googled a bit but can't find anything really helpful.
This is my .controller :
.controller('registerController', function($scope, $http) {
$scope.registerData = {firstname : null, lastname : null, login: null, password : null, email : null, city : null, postalcode : null, adress: null, country: null};
$scope.registerFunction = function() {
$http({
method: "post",
url: './php/registration.php',
data: {
firstname: $scope.registerData.firstname,
lastname: $scope.registerData.lastname,
login: $scope.registerData.login,
password: $scope.registerData.password,
email: $scope.registerData.email,
city: $scope.registerData.city,
postalcode: $scope.registerData.postalcode,
adress: $scope.registerData.adress,
country: $scope.registerData.country,
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
swal("Good job!", "You have been registered!", "success");
};
})
This is my form in html+bootstrap :
<div class="modal fade" id="registerModal">
<div class="modal-dialog">
<div class="modal-content" ng-controller="registerController">
<div class="modal-header"><h4 class="modal-title">Sign Up</h4></br><button type="button" class="close" data-dismiss="modal">×</button></div>
<div class="modal-body"><form>
<div class="row">
<div class="col-lg-6">
<label style="float: left;"><b>Firstname:</b></label>
<input type="text" ng-model="registerData.firstname" class="form-control">
<label style="float: left;"><b>Lastname:</b></label>
<input type="text" ng-model="registerData.lastname" class="form-control">
<label style="float: left;"><b><span class="redstar">*</span> Login:</b></label>
<input type="text" ng-model="registerData.login" class="form-control">
<label style="float: left;"><b><span class="redstar">*</span> Password:</b></label>
<input type="password" ng-model="registerData.password" class="form-control">
<label style="float: left;"><b><span class="redstar">*</span> Repeat Password:</b></label>
<input type="password" class="form-control">
</div>
<div class="col-lg-6">
<label style="float: left;"><b><span class="redstar">*</span> E-Mail:</b></label>
<input type="text" ng-model="registerData.email" class="form-control">
<label style="float: left;"><b>City:</b></label>
<input type="text" ng-model="registerData.city" class="form-control">
<label style="float: left;"><b>Postal Code:</b></label>
<input type="text" ng-model="registerData.postalcode" class="form-control">
<label style="float: left;"><b>Adress:</b></label>
<input type="text" ng-model="registerData.adress" class="form-control">
<label style="float: left;"><b>Country:</b></label>
<select class="form-control" ng-model="registerData.country" required>
<option ng-repeat="item in countries" value="{{item.id}}">
{{item.name}}
</option>
</select>
</div>
<div class="col-lg-12">
<p style="float:left;">Fields marked with <span class="redstar"><b>*</b></span> are required.</p></br>
</div>
</div>
</form></div>
<div class="modal-footer"><button type="button" class="btn btn-danger" data-dismiss="modal">Close</button><button type="button" class="btn btn-success" data-dismiss="modal" ng-click="registerFunction()">Sign Up</button></div>
</div></div>
</div>
This is how i execute it :
<?php
include_once 'config.php';
$data = json_decode(file_get_contents("php://input"));
$firstname = $data->firstname;
$lastname = $data->lastname;
$login = $data->login;
$password = $data->password;
$email = $data->email;
$city = $data->city;
$postalcode = $data->postalcode;
$adress = $data->adress;
$country = $data->country;
$dbh->query("INSERT INTO `accounts` (`account_id`, `firstname`, `lastname`, `login`, `password`, `email`, `city`, `postalcode`, `adress`, `country`, `role`)
VALUES (NULL,'".$firstname."','".$lastname."','".$login."',MD5('".$password."'),'".$email."','".$city."','".$postalcode."','".$adress."','".$country."', 0) ") or die(mysql_error());
$dbh = null;
?>
And this is my connection :
<?php
$hostname='localhost';
$username='root';
$password='';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=myshop",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
echo 'Connected to Database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
My question is how can i for example add and If in my controller like there is an error duplicate entry for 'login' i do something in my angular. So how can i catch the error in to my controller?
In addition to the great answer from #deceze, there is one thing that needs to be explained.
There are two kind of exceptions: expected and unexpected ones. And they should be treated differently.
One you asked for is an expected one. The username already taken is a regular case, I wouldn't call it an error from the application point of view. So the response should be regular as well. A meaningful message should be sent to Angular, and the latter should act accordingly: prompt a user to try another username.
Another thing is an unexpected error. Such as your database server is down. For this kind of error, no particular error message should be shown but a generic excuse and a suggestion to try later.
and now to the implementation: you should catch the expected error and shouldn't otherwise.
An example can be seen in my PDO tutorial:
try {
$pdo->prepare("INSERT INTO users VALUES (NULL,?,?,?,?)")->execute($data);
} catch (PDOException $e) {
$existingkey = "Integrity constraint violation: 1062 Duplicate entry";
if (strpos($e->getMessage(), $existingkey) !== FALSE) {
// Take some action if there is a key constraint violation, i.e. duplicate name
} else {
throw $e;
}
}
here you can see that a caught Exception should be tested against a list of expected errors and re-thrown id there is no match.
You cannot catch a server-side exception in client-side code, exceptions don't propagate across HTTP. You need to abstract that more: the client makes an HTTP request to the server, the server returns an HTTP status code and response content. If an exception, or anything else bad, happens on the server, the server signals that to the client using the HTTP status code. So if an exception happens, you set an appropriate code:
try {
...
} catch (PDOException $e) {
header('HTTP/1.0 500 Internal Server Error');
// Maybe: echo json_encode(['error' => 'You fool!']);
exit;
}
In fact, if you simply don't catch the exception and let PHP die with an unhandled exception error, the web server will by default respond with such a 500 status code.
On the client side, this will cause the $http promise to reject, and you can handle that:
$http(...)
.catch(response => {
console.error('Error fooing the bar', response.statusText);
// do something constructive
});
Pick an appropriate status code to respond with to distinguish various conditions: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
I created a form you know; text fields, radio buttons and the submit button
within the said form, I have a div enclosing a section of the radio buttons hidden and a text field upon page load using inline CSS display:none;
If the end user chose yes, the hidden fields will be displayed using a jquery function. If the user chose No or Not Sure, the form will remain hidden or become hidden using the same jquery function.
If the user chose No or Not Sure, i want to automatically assign values for the hidden fields and store them in database.
Here is my form:
<div id = "relation" style = "display: none;">
<p class= "form-p" >Who are you related o?</p>
<div class="form-group">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-4">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" autocomplete="off" name="family" value="Bride" required />Bride
</label>
<label class="btn btn-default">
<input type="radio" autocomplete="off" name="family" value="Groom" required />Groom
</label>
<label class="btn btn-default">
<input type="radio" autocomplete="off" name="family" value="Friend" required />Friend
</label>
<span class="error"><?php echo $famErr;?></span>
</div>
</div>
</div>
<p class = "form-p">Guests in your party, including yourself: </p>
<div class = "form-group">
<label class="control-label col-sm-4"></label>
<div class="col-xs-2">
<input type = "text" class = "form-control" name="num" placeholder = "0" required />
<span class="error"><?php echo $numErr;?></span>
</div>
</div>
</div> <!-- end of id relation-->
Here are the functions:
// function to add RSVP user entry to the database
public function user_attending_storage_RSVP($name, $email, $attend, $fam, $num){
$replies = "INSERT INTO rsvp (name, attending, family, total) VALUES (:name,:attending,:family,:total)";
try{
$query = $this->conn->prepare($replies);
$results = $query->execute(array(":name"=>$name, ":attending"=>$attend, ":family"=>$fam, ":total"=>$num));
}
catch(PDOException $e){
die($e->getMessage());
}
}
// function to add RSVP user entry to the database
public function user_not_attending_storage_RSVP($name, $email, $attend){
$replies = "INSERT INTO rsvp (name, attending, family, total) VALUES (:name,:attending,:family,:total)";
try{
$query = $this->conn->prepare($replies);
$results = $query->execute(array(":name"=>$name, ":attending"=>$attend, ":family"=>$fam, ":total"=>$num));
}
catch(PDOException $e){
die($e->getMessage());
}
}
Here's how I call the function on the webpage
// check for data in fields
if(isset($_POST['name']) ==true && isset($_POST['email']) ==true && isset($_POST['attending']) && isset($_POST['family']) && isset($_POST['num'])){
$name=test_input($_POST['name']);
$email=test_input($_POST['email']);
$attend=test_input($_POST['attending']);
$fam=test_input($_POST['family']);
$num=test_input($_POST['num']);
if($attend == "No" || $attend == "Not Sure"){
$fam = "nothing";
$num = 0;
//inserting user data from form into database
$genQuery->user_Not_attending_storage_RSVP($name, $email, $attend);
}
else{
//inserting user data from form into database
$genQuery->user_attending_storage_RSVP($name, $email, $attend, $fam, $num);
}
// send mail to user
$genQuery->user_invite_confirmation_RSVP($name, $email, $attend,$fam, $num);
}
You can use the getElementById() method...
if(getElementById('input_id').value() == 'no' || getElementById('user_id').value() == 'not sure'){getElementById('input_you_want_to_change).value('Defualt value')}
This will change the value if the user selects no or not sure. Then use PHP to store this new value in the database.