I usually create another page to do my php posts like this:
page1.php:
<form action="page2.php" method="post">
...
</form>
page2.php:
<?php
$var = $_POST['...'];
?>
one friend of mine told me that I should to this in the same page:
page1.php
<?php
if (isset($_POST['...'])){
...
}
else{
?>
<form action="page1.php" method="post">
...
</form>
<?php
}
?>
My question is, which one is a better or faster method and best practise?
thank you friends!
You can do it in both the ways you have mentioned .
its not like you "Should to this in the same page"
In first part you are passing the control from page1 to page2 ...which is done by submit button
So you can directly get the values using $_POST['...'];
Now in seccond part you are passing the control to same page , Since you are calling the same page on submit .
But here need to check if Post data has been set so for that you use isset method.
Most importantly you can use second solution if you want to stay on the same page after submission
Therefore, Use of isset() method in first part is a good habbit , but in
second solution is a necessity
In my opinion Better use another page so that even the code does not look messed up.
Related
I have form that calls php file like this (contact.php):
<form role="form" id="form1" method="post" class="validate" action="contact_actions.php" enctype="multipart/form-data">
contact_actions.php at the end calls back header('Location: contact.php');
I am a noob regarding php and having hard time finding exact example that will show me how to get some response from contact_actions.php, like error message or succeeded message... I've found some complicated solutions, but I am wondering is there some simple one with maybe global variable? I've tried with global variables and it didn't work, maybe with wrong ones and maybe in a wrong way. Also, what is the best solution?
You can:
Put code from contact_actions.php in a function.
This function can return true or false, and even fill an &$error
parameter.
Remove contact_actions.php
Change form action to contact.php
Inside contact.php, call that function, and show info according to
its result.
Don't use global variables, they're not useful and bad style.
Use $_GET.
Like:
header('Location: contact.php?success=1');
Then in contact.php
if ($_GET['success'] == 1) {
echo "The contact-form has been sent";
}
This is my super-simplified index.php:
<?php
require_once 'DeleteOrAdd.php'; // handles adding/deleting a db record
doAddDeleteRecord();
// other functions are called here, left out though for brevity
?>
Here's DeleteOrAdd.php (much simplified)
<?php
function doAddDeleteRecord()
{
echo <<<_END
<form action="index.php" method="post">
// the other form html not shown here
<input type="submit" value="ADD RECORD" />
</form>
_END;
// NOT SHOWN -- code to handle the form when it is POST'd
}
?>
So it's late 10:30pm, I'm new to PHP, okay /excuses.
Can't figure out how to do this.
I want to change my form action="index.php" above to form action="DeleteOrAdd.php"
(ie. I want to re-post to the same file that this form is in,
not to index.php, so the code is cleaner).
but it won't work because I have all the form-handling logic for the POST --
inside the doAddDeleteRecord() function, so if I set my form action="DeleteOrAdd.php"
it won't work.
Is it possible to do something like form action="DeleteOrAdd.php:doAddDeleteRecord()?
I don't want to put this in classes.
I also want to keep my index.php just as it is above -- calling functions and no major
inline code beyond that.
Any ideas?
Originally, all the code was inline inside index.php (got it from a PHP book's sample)
and I then divided the code into logically-named PHP files in the Netbeans project
to clean it up, and to put stuff in functions that get called from index.php.
remove the action value completly from the form, default it will post always back to the url on which it is displayed.
<form action="" method="POST">
Your application is not well structured. I would recommend to follow MVC pattern.
But for your current problem you can do something like this
just set the action to your <form action="DeleteOrAdd.php" or you can leave the action completely blank which post your data on the same file in which the form is created.
When the form is posted your could do below in your DeleteOrAdd.php file.
if (isset($_POST['submit']))
{
doAddDeleteRecord();// this will call your
}
but in this case you may have to change the code of your index.php
I think the problem you have here is being able to make your PHP page discern between whether or not its a fresh load or whether or not its submission of the form, and that is why your incorporating the index page in your action parameter. However, this is not necessary.
Set the id and name (for valid markup) attribute of your submit element to a unique name. Such as "form_submit" so here is an example.
<form action="" method="post">
<input type="submit" id="form_submit" name="form_submit" value="ADD RECORD" />
</form>
So what you put in your PHP script (doAddorDelete.php) is this ...
if (array_key_exists('form_submit', $_POST)) {
//this is the code to execute on form submit
//use print_r($_POST) to view variables you can use here
//make sure you validate all data passed here especially if using a database
//ie if MySQL
//$validated_userinput = mysql_real_escape_string(strip_tags(htmlentities(trim($_POST['userinput']))), $link_resource); for text
//(int) $_POST['userinput']; for numbers
} else {
echo <<<_END
<form action="" method="post">
// the other form html not shown here
<input type="submit" id="form_submit" name="form_submit" value="ADD RECORD" />
</form>
_END;
}
Hope this helps! :)
Foreword: Since you say this as a learning exercise, I'll skip past the sanctimonious manifesto on best practice and the many and sundry virtues of OOP. ;) Your book probably details every dire warning / stern lecture I'd normally prepend to a solution like this anyway.
Is it possible to do something like
form
action="DeleteOrAdd.php:doAddDeleteRecord()
?
In short, yes. The easiest way to accomplish your goal is to just reference your file in your form action, as you've done:
<!-- form.php -->
<form action="DeleteOrAdd.php" method="POST">
And then in DeleteOrAdd.php, trigger your function by testing the $_POST data your form submit will send in, like so:
<?php
// DeleteOrAdd.php
if(isset($_POST['some_form_variable']) && $_POST['some_form_variable'] != null) {
$data = array();
foreach($_POST as $post) {
array_push($data, $post);
}
doAddDeleteRecord($data);
}
function doAddDeleteRecord($data) {
// ...your processing code, etc.
The upshot to a purely procedural approach like you've specified is quite frankly, you can do stuff like this. You wouldn't want to develop like this in real life (skipping this deep-dive too, I guarantee your book explains why not in exhaustive detail.)
Important note!! Since I didn't see a return value in the code snippet you posted, and you say you're just getting started, I'm going to take a minute and point out a hidden pitfall here just in case:
--> Your code might work perfectly with those six lines I added above your function, and you'd never know it if you're not
returning a value (which proves the code ran, if nothing else) and
capturing said value so you can act on it / display it / otherwise show yourself that
a. something happened -- and ideally,
b. what that something was.
Otherwise, all you've got is ambiguity: no indication it's either working or breaking (not throwing errors, warnings, etc). Frustrating to debug, to say the least.
So, that stated -- presuming you've got your function returning something (true on success, string with a message, whatever) it probably goes something like this:
function doAddDeleteRecord($data) {
// ... your function code, etc.
$sql = "INSERT INTO mytable VALUES(".implode(',',$data).")";
if (mysql_query($sql) == true) {
$message = "Record saved";
} else {
$message = false;
}
return $message;
}
Any value your function returns needs a variable to capture it or it won't be set. Capture it with a variable assignment when you call your doAddDeleteRecord() function:
... // same 6 little lines of conditional code ...
}
$result = doAddDeleteRecord($data);
}
// maybe just echo it out or something...
echo $result;
-- or --
... // still the same 6 lines ...
}
$result = doAddDeleteRecord($data);
}
// maybe have a new test based on the outcome of the last one...
if ($result == false) {
// do something about the fail...
} elseif (is_string($result)) {
// do something about the success...
}
Good luck, HTH. :)
I Have a php form page where users fill the data and process page to add data to database, Its working fine, But problem is I need the results from process page to be displayed back on to my main page? How to get results back to main page?
In the form's action attribute, set the path to $_SERVER['PHP_SELF'] rather than processing file. This way, form will submit to same page where you can process it.
<form action="<?php echo $_SERVER['PHP_SELF'];?>">
.....
</form>
How about
<form action="mainPage.php" ...>
Simple and your Data will be on the main page.
Use sessions. In script assign a error message to session variable and do redirect. On script.php
$_SESSION['error'] = 'Incorrect email';
index.php
echo $_SESSION['error'];
Don't forget session_start() in begin of scripts.
There's a wide variety of ways, depending on what you're talking about. You'll likely want to use session variables, though. In the processing script:
<?php
start_session();
// Do your processing here
$_SESSION['myvar'] = $finished_data;
?>
And in the main page that called it:
<?php
session_start();
if(!empty($_SESSION['myvar'])) {
$data = $_SESSION['myvar'];
}
// Use $data here as you need
?>
Looks to me like you need to include some Javascript here, then post the returned data to wherever you want. there is.. post to same pagewith...document.getElementById('yourDiv').innerHTML = 'yourReturnedData';
or with $_GET variables.
example...
yoursite.com/yourPage.php?data1=data1&data2=data2
Get returned data by ...
$var1 = $_GET['data1'];
$var2 = $_GET['data2'];
Hope this is of use
So I have a form that I post to a page and in the form I'm posting certain variables that I build one of my queries with and then call them on my page. How can I post data and also build a query and display the answer on one call?
Maybe I'm not wording it right and I'm learning this stuff, but I just don't know. Should I post to an intermediate page first?
Example: form (variables A & B) to-> page (A & B used in query) and then result is on that same page.
can this be done and what's the method?
Thanks!
This is the basic priniciple, but you must sanitize you input data from the form. For example using mysql_real_escape_string().
But in a single page you can have code like this (it is not tested, I'm not able to on this computer):
<?php
if(isset($_POST['name']))
{
$query = "SELECT * FROM table WHERE firstname = '"+ mysql_real_escape_string($_POST['name']) +"'";
while($node = mysql_fetch_rows())
{
echo "The result: " . $node['id'];
}
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name" />
</form>
This will post to it self, run the query and echo the result, and show the form again.
For small tools and the like, this is an ok approach, but for larger websites I would recommend not mixing the request handling code with the html. Look into using a framework for applying the mvc pattern or something like that.
Without specific examples it's hard to write it, but it's fairly simple.
In a very basic way:
File1.php:
--your form submits to file2.php--
File2.php:
function processForm(inputs) [
--MySql query goes here--
]
function displayResults() [
--Process your query results--
]
processForm($_POST['vars']...);
displayResults();
Does that make sense? Simply make a function that processes and then displays the results again.
If you want to get really fancy you can even do it all in a single file, but you should probably master this technique first if you are first learning.
Let's say I have a page called display.php and the user is viewing display.php?page=3. I want to allow the user to do an action like voting via a POST request and then bring them back to the page they were on. So, If I do a POST request to display.php?page=3 would the page information also be available to the script?
The simple answer is 'yes'. You can use a GET-style URL as the submission URL for a POST form. PHP will have both the POST and GET information available to it in the usual ways when the form is submitted.
This is not to say that you should do this, but it will work.
In PHP, you can get request variables from the special global arrays:
$_GET['page'] (for GET requests)
$_POST['page'] (for POST requests)
$_REQUEST['page'] (for either)
It sounds like you are looking for "Redirect after Post", I would suggest separating display.php and vote.php into separate files. Vote looks something like this:
<?php
//vote.php
$page_number = (int)$_REQUEST['page'];
vote_for_page($page_number); //your voting logic
header('Location: display.php?page=' . $page_number); //return to display.php
Note that blindly accepting unsanitized form data can be hazardous to your app.
Edit: Some folks consider it bad form to use $_REQUEST to handle both cases. The hazard is that you may want to signal an error if you receive a GET when you expect a POST. Typically GET is reserved for viewing and POST is reserved for making changes (create/update/delete operations). Whether this is really a problem depends on your application.
Yes, the GET array is always filled with the URL parameters regardless of the request method. You can try it with a simple page like this:
<form action="test.php?a=b" method="post">
<input name="a"/>
<input type="submit"/>
</form>
<pre>
POST:
<?php print_r($_POST); ?>
GET:
<?php print_r($_GET); ?>
</pre>