I cannot figure out how to go about keeping the data saved on $myArray after hitting Save. Everytime i do that, it replaces the other input.
I need to be able to save all user enters and save in text file. basically keep saving data on array and update file as well.
Any suggestions?
<!DOCTYPE>
<html>
<body>
<form action="list.php" method="POST">
Name: <input type="text" name="name[]" /><br />
Email: <input type="text" name="name[]" /><br />
<input type="submit" name="save" value="Submit" /><br />
<?php
$myArray = array();
if (isset($_POST['save']))
{
array_push($myArray,$_POST['name']);
}
print_r($myArray);
?>
</body>
</html>
Every time your user hits Submit, there is a new request sent to your script.
The variable $myArray is created on the first line of your PHP code, and is an empty array.
Variables do not persist across requests. I suggest you use either a cookie, or a session variable for this.
Example of the latter is here:
<?php
session_start(); // This has to be done before any data is sent to the client
session_regenerate_id(); // Good practice to prevent session hijacking
?>
<!DOCTYPE>
<html>
<body>
<form action="list.php" method="POST">
Name: <input type="text" name="name[]" /><br />
Email: <input type="text" name="name[]" /><br />
<input type="submit" name="save" value="Submit" /><br />
<?php
if( !isset( $_SESSION['myArray'] ) || !is_array( $_SESSION['myArray'] ) )
{
$_SESSION['myArray'] = array();
}
if (isset($_POST['save']))
{
$_SESSION['myArray'][] = $_POST['name'];
}
print_r($_SESSION['myArray']);
// Here you can write the contents of $_SESSION['myArray'] to a file.
?>
</body>
</html>
This way you will keep track of it in the text file:
<html>
<body>
<form action="list.php" method="POST">
Name: <input type="text" name="name[]" /><br />
Email: <input type="text" name="name[]" /><br />
<input type="submit" name="save" value="Submit" /><br />
<?php
$myArray = array();
if (isset($_POST['save']))
{
$f = file_get_contents("myfile.txt");
$myArray = split($f, "\n");
array_push($myArray,$_POST['name']);
file_put_contents("myfile.txt", implode($myArray, "\n"));
}
print_r($myArray);
?>
</body>
</html>
(You may want to use PHP_EOL [or whatever that constant is - I always have to look it up] in place of "\n")
Since HTML is by nature transactional you do not keep track of ANYTHING except sessions, databases, files - any variables you have start over empty each time you load your page again.
Related
Here is a code that I've made:
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if(isset($_POST['name'])){
$sum+=1;
}
echo "sum = $sum";
?>
When I enter some text in the form and click Validate, the page display sum=1, but after this, when I enter nothing in the form and click Validate, the page STILL displays sum=1.
Why does the variable $sum is not reloaded between the two Validate ? Is there a way to escape it ?
Thanks
This will solve the issue
<?php
$sum=0;
if(isset($_POST['name']) && $_POST['name'] != ''){
$sum+=1;
}
echo "sum = $sum";
?>
This is because isset() checks for the existence of the $_POST variable. In your case, the $_POST variable exists and has an empty string value.
Your code will work if you change isset() to !empty() like so;
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if(!empty($_POST['name'])){
$sum+=1;
}
echo "sum = $sum";
?>
More about the empty() function here.
Another way would be to check the request that your client has made on your page. So that if it is a simple refresh (not with a form refresh), it is a GET request and so, the variable should not be incremented and if the form has been sent, then you can do whatever you want such as incrementing the data.
So if the client is sending the form with an input text filled, then you can increment the value. In all other cases, the value should remain a zero.
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['name']) && !empty($_POST['name']))
{
$sum++; /* strictly equivalent to: $sum += 1; */
}
?>
<samp>sum = <?php echo $sum; ?></samp>
Try this
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" name="submit" value="Validate" />
</form>
<?php
$sum=0;
if(isset($_POST['submit'])){
$sum+=1;
}
echo "sum = $sum";
?>
You can try below:
if(isset($_POST['name']) && strlen($_POST['name'])>0){
$sum+=1;
You have the code appending 1 to variable $sum
but your if statement is based on the name field being passed.
Not if the name field has any data in it.
So... you have made your code add 1 as long as name field is passed,
regardless if it has text input or not.
Also, you should reassign the varible to reset it.
+= should just be =
<form method="post" action="test.php">
//----------------------------- add empty value to input ------------
<input type="text" name="name" value="" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if(isset($_POST['name'])){
$sum=1;
}
echo "sum = $sum";
?>
Here's the thing. When I submit the form, it works every time UNLESS my Title field is blank.
My HTML on page:
Title: <input type="text" name="title"><br />
Description:<br />
<textarea name="desc"></textarea><br /><br />
Location: <input type="text" name="where"><br />
<input type="submit" value="Submit">
My PHP having to do with the title input, on the other page:
if(empty($_POST["title"]) or !ctype_alpha(str_ireplace(" ","",$_POST["title"]))){
$ge=True;
$et=True;
}
The above if statement just checks to see if the title entered contains letters and spaces ONLY, and to make sure it isn't blank.
It's only when that one text field is blank, and nothing else.
I'm new to PHP so any help would be awesome.
Thanks for your time!
- Eric
EDIT
Sorry, should have been more descriptive. The page acts as if it's trying to submit the form (the spinning loading icon thing is there), but it never makes it to the process page. The form page just becomes unresponsive.
You can try this,
<html>
<body>
<form method="POST">
Title: <input type="text" name="title"><br />
Description:<br />
<textarea name="desc"></textarea><br /><br />
Location: <input type="text" name="where"><br />
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
if(empty($_POST["title"]) or !ctype_alpha(str_ireplace(" ","",$_POST["title"])))
{
$ge=True;
$et=True;
echo 'empty title';
exit();
}
echo 'form submitted';
}
?>
Sorry if this is a rather basic question.
I have a page with an HTML form. The code looks like this:
<form action="submit.php" method="post">
Example value: <input name="example" type="text" />
Example value 2: <input name="example2" type="text" />
<input type="submit" />
</form>
Then in my file submit.php, I have the following:
<?php
$example = $_POST['example'];
$example2 = $_POST['example2'];
echo $example . " " . $example2;
?>
However, I want to eliminate the use of the external file. I want the $_POST variables on the same page. How would I do this?
Put this on a php file:
<?php
if (isset($_POST['submit'])) {
$example = $_POST['example'];
$example2 = $_POST['example2'];
echo $example . " " . $example2;
}
?>
<form action="" method="post">
Example value: <input name="example" type="text" />
Example value 2: <input name="example2" type="text" />
<input name="submit" type="submit" />
</form>
It will execute the whole file as PHP. The first time you open it, $_POST['submit'] won't be set because the form has not been sent.
Once you click on the submit button, it will print the information.
I am learning PHP now, so pardon my silly question which I am not able to resolve.
I have created a simple web form where in I display the values entered by a user.
function submitform()
{
document.forms["myForm"].submit();
} // in head of html
<form action ="res.php" id="myForm" method="post" >
Name: <input type="text" name="name" size="25" maxlength="50" /> <br> </br>
Password:<input type="password" name="password" size="25" maxlength="50" />
Description: <textarea name="editor1"> </textarea>
<input type="submit" value="Submit" onclick="submitForm()" />
</form>
and res.php contains:
foreach($_POST as $field => $value)
{
echo "$field = $value";
}
When I click on the submit button, I just get a blank page without any values from the form. Can anyone please let me know what am I missing?
There's no need for the javascript. This should do:
<form action ="res.php" id="myForm" method="post" >
Name: <input type="text" name="name" size="25" maxlength="50" /> <br> </br>
Password:<input type="password" name="password" size="25" maxlength="50" />
Description: <textarea name="editor1"> </textarea>
<input type="submit" value="Submit" />
</form>
Let's start with fixing errors:
JavaScript is case-sensitive. I see that your function name is submitform and the form's onclick calls submitForm.
The javascript is not really necessary from what you've shown us, I would try this on a single php page and see if it works:
Create a test.php file for test purpose:
<?php
if($_POST){
foreach($_POST as $key=>$value){
echo "$key: $value<br />";
}
}else{
<form action="test.php" method="post">
<input type="text" value="1" name="name1" />
<input type="text" value="2" name="name2" />
<input type="submit" value="submit" name="Submit" />
</form>
}
?>
If it does work, slowly work your way into your current form setup to see what is breaking it. If it doesn't work, there's something larger at play.
There are 2 things you should do now.
Remove the JavaScript function to submit the form. It's not required (or necessary). The default behavior of a submit button is to... well... submit. You don't need to help it with JavaScript.
Enable error display by using error_reporting(E_ALL).
After you do both things, you should be able to debug and assess the problem much more easily.
Put your php code inside php tags!
<?php
foreach($_POST as $field => $value)
{
echo $field ." = ." $value.'<br />';
}
?>
If you do
<?php
print_r($_POST);
?>
what do you get?
If this still doesn't work, does your server parse php?
Create the file test.php and access it directly http://localhost/test.php or whatever your URL is
<?php
echo 'Hello';
?>
if this doesn't work..it's a whole diferent problem
You can submit an HTML form using PHP with fsubmit library.
Example:
require_once 'fsubmit.php';
$html = "<form action ='res.php' method='post'><input type='text' name='name'/></form>";
$form = new Fsubmit();
$form->url = 'http://submit_url_here.com';
$form->html = $html;
$form->params = ['name'=>'kokainom'];
$response = $form->submit();
echo $response['content'];
I have the basic html form echoed through php:
<html>
<body>
<?php
if (isset($_GET["pk"]))
{ $pk = $_GET["pk"];}
echo '<form action="up.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>';
?>
</body>
</html>
I would like to pass the value of pk to up.php
Modifying action="up.php?pk=$pk" did not work.
Use a hidden field:
<input type="hidden" name="pk" value="<?php echo $pk; ?>">
By the way, printing large amounts of HTML like you have there is ugly. Consider either stepping out of PHP to do so, using HEREDOC, a template engine, or a framework.
EDIT:
As noted below, you should not print GET and POST data back to the page without sanitizing it first. Assuming pk is a primary key, you should wrap $pk above with the intval function, at the very least.
I agree with all the comments regarding some kind of input control of the $_GET['pk'] variable. I would recommend the filter module in php, which is pretty much a default installed module I believe.
<html>
<body>
<?php
$param = filter_input(INPUT_GET, 'pk', FILTER_SANITIZE_ENCODED);
?>
<form action="up.php<?php echo (isset($param) && $param != false) ? '?pk=' . $params : ''); ?>" method="post"enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
You can find more information about the filter module here: link text
I also agree with Paolo Bergantino, this is not the prettiest way to do it, and a template engine, heredocs or regexp could be a better way of increasing the readability and maintainability of the system.
You can't use a variable inside a single-quoted string:
$pk = 123;
echo 'Hello $pk'; // echos Hello $pk
echo "Hello $pk"; // echos Hello 123
echo 'Hello ' . $pk; // echos Hello 123
The best way to pass it through would be as a hidden field inside the form
Try sth like this:
<html>
<body>
<?php
$params = "";
if (isset($_GET["pk"]))
{ $params = "?pk=" . $_GET["pk"];}
echo '<form action="up.php' . $params . '" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>';
?>
</body>
</html>
Of course you should be aware that $_GET["pk"] may contain pretty much anything, so think about some kind of input sanitization.