Single form multiple submit into same array - php

I was trying to push with a single form using the $_POST method multiple times the same form (with different values) until the array index is 4 (or a number I decide).
So with this html form i want to press submit, push the values into array, then refresh page, reinsert different values and so on until the condition is true.
<?php
if (!isset($count)) {
$person = array(
array(
'name' => '',
'surname' => '',
'phoneNumber' => ''
)
);
}
var_dump($person);
if (!isset($_POST['submit'])) {
echo "<form action=\"index.php\" method=\"post\">
<label for=\"name\">Name</label>
<input type=\"text\" name=\"name\" required>
<br>
<label for=\"surname\">Surname</label>
<input type=\"text\" name=\"surname\" required>
<br>
<label for=\"phoneNumber\">Phone Number</label>
<input type=\"text\" name=\"phoneNumber\" required>
<br>
<input type=\"submit\" value=\"Submit\" name=\"submit\">
</form>";
$count = 0;
} else {
$name = $_POST['name'];
$surname = $_POST['surname'];
$phoneNumber = $_POST['phoneNumber'];
if (count($person) <= 2) {
array_push($person, $name, $surname, $phoneNumber);
//echo "<meta http-equiv=\"refresh\" content=\"0\">";
//echo "Sto inserendo persone";
//echo count($persone);
echo count($person);
//var_dump($persone);
//print_r($persone);
} else {
var_dump($person);
};
}
?>
I was thinking about using $_SESSION but I don't have an idea about how to use it.
I don't want to use AJAX or jQuery or Javascript only pure PHP.

The example below shows always the form and your actual persons array. If you submit the form, your data will add to the array until it counts more than three entries. I think that is what you are looking for:
<?php
session_start();
if (!isset($_SESSION['persons'])) {
$_SESSION['persons'] = [];
}
if(isset($_POST['submit'])) {
if (count($_SESSION['persons']) <= 2) {
$_SESSION['persons'][] = array(
'name' => $_POST['name'],
'surname' => $_POST['surname'],
'phoneNumber' => $_POST['phoneNumber']
);
}
}
?>
<pre><?php var_dump($_SESSION['persons']); ?></pre>
<form action="index.php" method="post">
<label for="name">Name</label>
<input type="text" name="name" required><br>
<label for="surname">Surname</label>
<input type="text" name="surname" required><br>
<label for="phoneNumber">Phone Number</label>
<input type="text" name="phoneNumber" required><br>
<input type="submit" value="Submit" name="submit">
</form>
With the following line of code you can clear you array if you need to:
$_SESSION['persons'] = [];

Related

How to check if required fields are filled in or not?

Using core PHP only and nothing else, like JavaScript or clientside programming, I need PHP to check if the form's required fields are filled in or not, and display error message if missed. I need to check using procedural style programming as I'm not into OOP yet and don't understand it.
Html Form
<html>
<head>
<title>
Searchengine Result Page
</title>
</head>
<body>
<form method = 'POST' action = "">
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<label for='url'>url</label>
<input type='url' name='url' id='url' required>
<br>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' required>
<br>
<label for='description'>description</label>
<input type='text' name='description' id='description' required>
<br>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' required>
<br>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' required>
<br>
<button type='submit'>Search!</button>
</form>
</body>
</html>
Php Form Validator
<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels_count = count($required_labels);
for($i=0; $i!=$required_labels_count; $i++)
{
if(!ISSET(in_array(($_POST['$required_labels[$i]']),$required_labels))) //Incomplete line as I don't know how to complete the code here.
{
echo 'You must fill-in the field' .'Missed field\'s label goes here'; //How to echo the missed field's label here ?
}
}
?>
I know I need to check against associated array values as it would be easier and less code, but I don't know how to do it.
Notice my error echo. It's incomplete as I don't know how to write that peace of code.
How would you check with the shortest possible code using procedural style?
Anything else I need to know?
NOTE: I do not want to be manually typing each $_POST[] to check if the required ones are filled in or not. I need PHP to loop through the $required_labels[] array and check. Or if you know of any shorter way of checking without looping then I want to know.
First we will have an empty $errors array, and then we will apply the validations, and if any of them fails, we will populate the $errors.
Finally using a helper function errorsPrinter we will print the errors under their labels.
For you PHP validation part use the below code. Note that I also added the part to validate the string and int types too.
<?php
$ints_labels = array('submission_id','website_age');
$strings_labels = array('url','anchor','description','keyphrase','keyword');
$required_labels = array('url','anchor','description','keyphrase','keyword');
$inputs = $_POST;
$errors = [];
foreach($required_labels as $label) {
if(!isset($inputs[$label]) || empty($inputs[$label])) {
$errors[$label] = array_merge(
["You must fill-in the field."],
$errors[$label] ?? []
);
}
}
foreach($strings_labels as $label) {
if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_string($inputs[$label])) {
$errors[$label] = array_merge(
["This input should be string"],
$errors[$label] ?? []
);
}
}
foreach($ints_labels as $label) {
if(isset($inputs[$label]) && !empty($inputs[$label]) && !is_int($inputs[$label])) {
$errors[$label] = array_merge(
["This input should be int"],
$errors[$label] ?? []
);
}
}
function errorsPrinter($errors, $key)
{
$output = '<ul>';
if(!isset($errors[$key])) {
return;
}
foreach($errors[$key] as $error) {
$output = $output. '<li>' . $error . '</li>';
}
print($output . '</ul>');
}
?>
inside the form you can do something like this:
<form method='POST' action="">
<?php errorsPrinter($errors, 'submission_id') ?>
<label for='submission_id'>submission_id</label>
<input type='text' name='submission_id' id='submission_id'>
<br>
<?php errorsPrinter($errors, 'website_age') ?>
<label for='website_age'>website_age</label>
<input type='text' name='website_age' id='website_age'>
<br>
<?php errorsPrinter($errors, 'url') ?>
<label for='url'>url</label>
<input type='url' name='url' id='url' >
<br>
<?php errorsPrinter($errors, 'anchor') ?>
<label for='anchor'>anchor</label>
<input type='text' name='anchor' id='anchor' >
<br>
<?php errorsPrinter($errors, 'description') ?>
<label for='description'>description</label>
<input type='text' name='description' id='description' >
<br>
<?php errorsPrinter($errors, 'keyphrase') ?>
<label for='keyphrase'>keyphrase</label>
<input type='text' name='keyphrase' id='keyphrase' >
<br>
<?php errorsPrinter($errors, 'keyword') ?>
<label for='keyword'>keyword</label>
<input type='text' name='keyword' id='keyword' >
<br>
<button type='submit'>Search!</button>
</form>
Note that the errorsPrinter is just a helper and you can remove it and use $errors array as you want. The sample output of errors is like this:
[
"url" => ["You must fill-in the field."],
"anchor" => ["You must fill-in the field."],
"description" => ["You must fill-in the field."],
"keyphrase" => ["You must fill-in the field."],
"keyword" => ["You must fill-in the field."],
"website_age" => ["This input should be int"]
]
$errors = [];
foreach($required_labels as $field) {
if (!isset($_POST[$field]) || $_POST[$field] == '') {
$errors[$field] = "{$field} cannot be empty";
// echo "${field} cannot be empty";
}
}
And then to output those errors:
<?php
if (count($errors)) {
?>
<div id='error_messages'>
<p>Sorry, the following errors occurred:</p>
<ul>
<?php
foreach ($errors as $error) {
echo "<li>$error</li>";
}
?>
</ul>
</div>
<?php
}
And you could directly output the errors next to the input as well:
<input type="text" id="first_name" name="first_name" placeholder="First Name" />
<?php if (isset($errors['first_name'])) echo "<div class='error_message'>{$errors['first_name']}</div>";?>

Form (htm & ajax) not registering

My AJAX code is refusing the post what is being filled into an html form. Rather than the actual contents, my txt file is just filling up with the words 'firstname lastname age'. Where am I going wrong?
(I have a submit button that, when pressed, will hide the div and open another one - don't know if this is important information)
This is the HTML:
General intro
<form action="action_page.php">
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
<br>
Age (in numbers; e.g., "47", not "forty-seven"):<br>
<input type="text" name="age">
<br><br>
</fieldset>
</form>
<p><button type=button id='Submit0'>Submit my information</button></p>
This is the code in my action_page.php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
$out;
$result = file_put_contents("log.txt", PHP_EOL ."firstname" . $firstname . " lastname " . $lastname ."age" . $age, FILE_APPEND);
if ($result !== FALSE) {
$out = [ "message" => "success!", "status" => 200];
}
else {
$out = [ "message" => "error saving file", "status" => 500];
}
echo json_encode($out);
exit();
This doesn't look like an Ajax to me,
but you should be able to solve your issue by changing
<form action="action_page.php">
to
<form action="action_page.php" method="POST">

my contact form isn't working properly; could be the logic

it keeps saying the fields are empty even when everything is correct. Heres my code:
<p>*All Fields Required</p>
<?php
if(!empty($reply)){
echo "<p class='notify'>$reply</p>";
}
unset($reply);
?>
<form method="post" action="index.php" id='contact'>
<fieldset>
<label>Name</label>
<input type='text' id="name" name="name" placeholder="type here" required value='<?php echo $name; ?>'>
<label>Email</label>
<input type='email' id="email" name="email" placeholder="type here" required value='<?php echo $email; ?>'>
<label>Message</label>
<textarea id="message" name="message" placeholder="type here" required><?php echo $message; ?> </textarea>
<p>Answer the following CAPTCHA question: </p>
<label for="captcha">What color is Snow Whites hair?</label>
<input type='text' name='captcha' id='captcha' size='5'required><br>
<label for='action'> </label>
<input id="submit" name="submit" type="submit" value="submit"><br>
</fieldset>
</form>
heres my index.php document:
<?php
if($_POST['action']=='submit'){
$name=$_POST['name'];
$email=$_POST['email'];
$message=$_POST['message'];
$captcha=strtolower($_POST['captcha']);
}
if(empty($name)||empty($email)||empty($message)){
$reply='Sorry, one or more fields are empty. All fields are required.';
include 'contactform.php';
exit;
}
if(empty($captcha)|| $captcha != 'black'){
$reply='The captcha answer is incorrect.';
include 'contactform.php';
exit;
}
$finalmessage="Name:$name\n";
$finalmessage .="Email: $email\n";
$finalmessage .="Message: \n$message";
//sending the message
$to="rachel14yancey#gmail.com";
$from="From: $email";
$result= mail($to, $finalmessage, $from);
//Letting visitors know what happened
if($result ==TRUE){
$reply = "Thank you $name for contacting us.";
unset($name);
unset($email);
unset($message);
include 'contactform.php';
exit;
} else{
$reply='Sorry $name. There was an error and the message could not be sent';
unset($name);
unset($email);
unset($message);
include 'contactform.php';
exit;
}
?>
You have no form field named action, therefore
if($_POST['action']=='submit'){
will ALWAYS evaluate to false, leaving all of the vars you're trying to create undefined.
You probably want $_POST['submit'] instead, as that's the name of your actual submit button.
<input id="submit" name="submit" type="submit" value="submit"><br>
^^^^^^^^^^^^^^^^^^^^^^^^^^^
This is what the form submits:
*var_dump($_POST)
**array (size=5)
'name' => string 'John Doe' (length=6)
'email' => string 'John.Doe#mail' (length=13)
'message' => string 'Blah Blah Blah' (length=10)
'captcha' => string 'White' (length=5)
'submit' => string 'submit' (length=6)**
Instead of $_POST["action"] you can use $_POST["submit"] and it should work.

how to store multiple array of same name from one form

suppose i m trying to store name,phone email of three person from one form here is my code..
<form method="post" action="demo.php">
<input type="text" name="name[]">
<input type="text" name="phone[]">
<input type="text" name="email[]">
<br>
<input type="text" name="name[]">
<input type="text" name="phone[]">
<input type="text" name="email[]">
<br>
<input type="text" name="name[]">
<input type="text" name="phone[]">
<input type="text" name="email[]">
<br>
<input type="submit">
</form>
now code of demo.php which is my action page...
foreach(($_POST['name']as $id)
{
$name= mysql_real_escape_string($id);
$query1 = "INSERT INTO list (name,phone,email) VALUES ('$name','$_POST[phone]',$_POST[email])";
$query = mysql_query($query1);
}
if($query)
{
return true;
}
else{
echo "Something Wrong";
}
its storing name of three people correctly but not storing phone and email of three people
i tried with for loop also but not getting result,plz anyone tell me how to store multiple array from a single form.
You can do this:
// variables of the form
$phone = $_POST['phone'];
$email = $_POST['email'];
foreach($_POST['name']as $k => $id)
{
$name= mysql_real_escape_string($id);
$query1 = "INSERT INTO list (name,phone,email) VALUES ('$name','$phone[$k]','$email[$k]')";
$query = mysql_query($query1);
}
if($query)
{
return true;
}
else{
echo "Something Wrong";
}

insert database nusoap-complexType

I want to create insert database a web service from :
http://www.discorganized.com/php/a-complete-nusoap-and-flex-example-part-1-the-nusoap-server/
Here's my script :
<?php
require_once 'lib/nusoap.php';
$client= new nusoap_client("http://127.0.0.1/test2/index.php", false);
$in_contact=array ('first_name'=>$_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'phone_number' => $_POST['phone_number'],);
$result = $client->call('insertContact', $in_contact);
if ($result){
echo "OK";
} else {
echo "Error";
}
?>
despite increasing ID, why the other columns remain empty ?
please help me, thank you.
The <form> code..
< form action="Contact.class.php" method="GET" > Nama Depan:<br> <input type="text" name="first_name"/><br> Nama Belakang:<br> <input type="text" name="last_name"/><br> Email:<br> <input type="text" name="email"/><br> Telepon:<br> <input type="text" name="phone_number"/><br><br> <input type="submit" value="Submit"/><br> < /form >
As you can see the method is GET , Change that to POST
Like this...
<form action="Contact.class.php" method="POST" >
The fixed <form> code.. You had a lot of indentations gone wrong..
<form action="Contact.class.php" method="POST" >
Nama Depan:<br> <input type="text" name="first_name"/><br>
Nama Belakang:<br> <input type="text" name="last_name"/><br>
Email:<br> <input type="text" name="email"/><br>
Telepon:<br> <input type="text" name="phone_number"/><br><br>
<input type="submit" value="Submit"/><br> </form>
<?php
require_once 'lib/nusoap.php';
$client= new nusoap_client("http://127.0.0.1/test2/index.php", false);
$in_contact=array ('first_name'=>$_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
'phone_number' => $_POST['phone_number'],);
$result = $client->call('insertContact', array($in_contact));
if ($result){
echo "OK";
} else {
echo "Error";
}
?>

Categories