Eds
Eds

Reputation: 575

Using $_GET in PHP include with variable in the include URL

Firslty, please forgive the ineloquent phrasing of my question.

What I am trying to do, is create a simple odbc script, and store it in a file which will be included in my main PHP file several times with different variables.

When including them, I want to specify some variables to pass to it.

My example would be:

Main page

include("table-fields.php?table=sometable");

table-fields.php

$table = $_GET['table'];
odbc_exec(some database function WHERE TBL= $table);

However, if my understanding is correct, as $_GET is global, it would be looking for main.php?table=

Would the better choice be to just set the variable before including, e.g.:

$table = some table;
include("table-fields.php");

table-fields.php

odbc(some database function WHERE TBL= $table);

I want to try and avoid that if possible.

Thanks, Eds

Upvotes: 1

Views: 3398

Answers (2)

Alvaro
Alvaro

Reputation: 41605

You have to declare the variable before the include and it will be available in the code under it.

$_GET is used to get data from HTTP request.

As you pointed out, this would be the correct way:

$table = some table;
include("table-fields.php");

Just imagine the include as a copy and paste inside your code. The code inside the included content will be replazing the include call.

Upvotes: 0

adeneo
adeneo

Reputation: 318212

When including a file, the contents of that file is outputted into the current file, it's not requested with HTTP, so all you need to do is :

$table = "sometable";

include("table-fields.php");

and in the included file, just use the variable :

odbc(some database function WHERE TBL= $table);

as the included content would work just like if you wrote it in the main file etc.

Upvotes: 2

Related Questions