问题
I have a page, q.php
, that is a user submitted post defined by its id, (for example, q.php?id=1
would be a certain post that uses the $id
variable to pull all the rest of the information from the database).
I am trying to code a comment submission on the same page, and account for the fact that a user might not enter anything into the field. If this happens, I want the page (e.g. q.php?id=1
) to load again with an error message.
I can do the error message with an empty variable that is then given a value by the php file that the form activates. However, I am having a problem navigating back to the specific post. I tried to use include('q.php?id=$id)
where $id is set to a number, but I understand that this is not its purpose and it does not accept variables
What should I be using instead?
EDIT
answer.php (file that the form activates):
require 'q.php';
$_GET['id'] = $id;
$_SESSION['error'] = "Please fill in all of the fields.";
q.php:
if ($_SESSION['error'] !== 0) {
echo "<p style='color: #AA1111;'>".$_SESSION['error']."</a>";
unset($_SESSION['error']); // this isn't happening...
}
回答1:
If you really must include the page inline, you can always modify $_GET
:
$_GET['id'] = $id;
require 'q.php';
But an error message sounds like it could be accomplished with a session variable or a redirect. A redirect could look something like:
header('Location: q.php?id=' . $id . '&error=The+error');
exit();
Then, you check for $_GET['error']
in q.php
. Using a session variable for that would be much the same, except instead of adding error
as a querystring parameter, you use $_SESSION['error']
and unset
it immediately.
回答2:
You could use header("Location: q.php?id=$id"); exit;
, but you would need some other way to send the error message (example: save it in $_SESSION
)
You might be able to set the $_GET
array how you want it - in this case, $_GET = Array("id"=>$id);
then include("q.php")
. This is generally considered haxy, though, and may result in problems if you don't use include_once
properly.
来源:https://stackoverflow.com/questions/14007750/php-redirect-to-page-with-variable-in-url