0

Suppose I've many tables in a mySQL database. Now in a PHP page named "A.php" I've selected a particular table using textbox and viewed the query on another PHP page named "B.php". Suppose the variable to get the table i used is,

$tablename=$_POST['textbox'];

And the query is,

$sql="SELECT * FROM $tablename WHERE id= '$id'";

Then, suppose I inserted a record & now, I want to view my record in another PHP page named "C.php" but I've selected the table in "B.php" as a variable & I've many tables but I want to have that particular table which is selected in "B.php". How can I do that? Badly need this help. Tnx in advance!

Sin Oscuras
  • 33
  • 1
  • 4

2 Answers2

2

You can store the table name in the user's session to make it persistent across page loads.

First, start the session. This needs to be added to the top of A.php, B.php and C.php:

session_start();

Next, store the data in a session variable:

$_SESSION['tablename'] = $_POST['textbox'];

Then you can use that value anywhere that you need it in any script that accesses the session:

$tablename = $_SESSION['tablename'];

Note that, as the commenters indicated, your MySQL statement is open to SQL injection. If you must use mysql_* functions, at least clean the data:

$tablename = mysql_real_escape_string( $_SESSION['tablename'] );

Better yet would be to disallow the user from entering a table name directly: Instead, allow them to select from a list and do the translation internally so that you can ensure that the table name is valid and well-formatted.

For more information, see How to prevent SQL injection in PHP?

Finally, consider moving away from the deprecated mysql_* functions to the mysqli or PDO. These API's provide a host of features to help you protect your data.

Community
  • 1
  • 1
George Cummins
  • 28,485
  • 8
  • 71
  • 90
1

Use session to keep your data persistent across scripts (recommended) or pass the value as GET variable. But whatever you will do, become familiar with SQLInjection first as your code is like asking for troubles.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141