How do I pass a variable to a file that I include?
I am trying to pass a variable to a included file. I have done something like this:
$id = $_GET['id'];
include('myfile.php');
And the file 'myfile.php' contains a form and a su开发者_StackOverflow社区bmit button. It's processing page is 'process.php' and in it, I have done:
$_id = var_dump($id);
// insert query
But I did not get the value of the variable, so 0 is inserted into the table.
Is there any other simpler way of doing it?
Thanks!
Functions.
Have myfile.php
declare a function (e.g. myfunction), which you call in the including script.
For example:
// main.php
<?php
include('myfile.php');
process_data($_GET['id']);
// myfile.php
<?php
function process_data($id) {
$query = 'SELECT * FROM foobar WHERE id = ' . mysql_real_escape_string($id);
// ...
}
If you really want to pass the variable as a global, and you're referencing the global in a function or method, be sure to reference it as $GLOBALS['varname']
or to use global $varname
:
function process_data() {
$id = &$GLOBALS['id'];
// or
global $id;
// ...
}
you have to pass over the value of $id inside your form in myfile.php
example:
<form action="process.php" method="post">
<input type="hidden" name="id" value="<?= $id ?>">
<!--- rest of your form -->
</form>
in your process.php, get the id back as following and do then your query.
$form_id = $_POST['id'];
精彩评论