Jump to content

Make MYSQL Table a PHP Variable


Scruffy

Recommended Posts

Hi,

 

I was wondering if anyone knows if there is away to make the selection of table from MYSQL to be a php variable.

 

Example is below:

 

$id = $_GET['id'];
$query_tester= "SELECT * FROM `$id` WHERE db_title = '$id'";

 

Thanks for your help!

Link to comment
Share on other sites

I have a large database with multiple tables in it. I would like to use a variable from the current page URL to select the correct table from the database.

 

I'm not sure if that helps explain it or not. Sorry I'm terrible at explaining coding.

Link to comment
Share on other sites

<?php
$table_name = array_key_exists( 'tablename', $_GET ) ? $_GET['tablename'] : '';
if( ! preg_match( '/^[a-zA-Z0-9_]+$/', $table_name ) ) throw new Exception( '$table_name is invalid: ' . var_export( $table_name, true ) );

$select_stmt = "
    SELECT *
    FROM `{$table_name}`
    WHERE 1=1
";
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.