title: PHP: How to use string variable as table in sql query (PDO)
body: <p>I would like to make a general function to select last inserted id's of different tables.</p>
  
  <p>I already tried multiple things, this might be the best effort (in db.inc.php);</p>
  
  <pre><code>&lt;?php
  define( 'DB_HOST', 'localhost' );
  define( 'DB_NAME', 'modlar' );
  define( 'DB_USER', 'root' );
  define( 'DB_PASS', 'password' );
  
  function verbinden(){
    $verbinding = 'mysql:host=' . DB_HOST . ';DB_NAME=' . DB_NAME;
    $db = null;
  
    try{
      return new PDO( $verbinding, DB_USER, DB_PASS );
    }catch( PDOException $e ){
      return NULL;
    }
  }
  
  function loopdoor( $naam, $ding){
    $regels = '';
    if( is_array($ding) || is_object($ding)):
      $wat = (is_array($ding)? 'array' : 'object');
      $regels .= '&lt;strong&gt;'.$naam.'['.$wat.']&lt;/strong&gt;&lt;ul&gt;';
      foreach( $ding as $k =&gt; $v):
        $regels .= loopdoor( $k, $v);
      endforeach;
      $regels .= '&lt;/ul&gt;';
    else:
      $regels .= '&lt;li&gt;&lt;strong&gt;'.$naam.'&lt;/strong&gt; =&gt; '.$ding.'&lt;/li&gt;';
    endif;
    return $regels;
  }
  
  function last_id( &amp;$db , $table, $column){
    if( is_null( $db ) ) return array();
  
    $sql = "
      SELECT
        max(modlar.table.column)
      FROM
        modlar.table";
  
    $vraag = $db-&gt;prepare( $sql );
    $vraag-&gt;bindValue( ':table', $table, PDO::PARAM_STR );
    $vraag-&gt;bindValue( ':column', $column, PDO::PARAM_STR );
    $vraag-&gt;execute();
    return $vraag-&gt;fetchAll( PDO::FETCH_OBJ );
  }
  </code></pre>
  
  <p>Where modlar is my database. And my variables (in db.php);</p>
  
  <pre><code>&lt;?php
  require_once 'db.inc.php';
  
  // Verbinden met database
  $db = verbinden();
  if( is_null($db))
    die('&lt;h1&gt;Error&lt;/h1&gt;');
  
  echo 'done';
  
  $table = 'time';
  $column = 'time_id';
  $last = last_id($db, $table, $column);
  echo '&lt;ul&gt;'.loopdoor('all data', $last).'&lt;/ul&gt;';
  ?&gt;
  </code></pre>
  
  <p>But I dont get any data on my screen (and no error). However, when I add the variables directly to the code, I'll get the last id of that table. So like;</p>
  
  <pre><code>  $sql = "
      SELECT
        max(modlar.time.time_id)
      FROM
        modlar.time";
  </code></pre>
  
  <p>What is going wrong?</p>