Select a table (FROM) by row

Is it possible to use a dynamic value inside a SELECT FROM sql command?

Database->prepare("SELECT bomb FROM ? WHERE id=?")
    ->execute($strTable,$strID);

result:

Fatal error: uncaught exception. Exception with message. Request error: you have an error in the SQL syntax; check the manual that matches your MySQL server version for the correct syntax used next ...

+5
source share
4 answers

Assuming $strTable- from a safe source, just use

Database->prepare("SELECT bomb FROM $strTable WHERE id=?")
    ->execute($strID);
+3
source

No. The table name cannot be a query parameter. First you need to build a query string by combining the table name.

+6
source

te bindParam. , , PHP-, @Alex. :

<?php
$stmt = $dbh->prepare("SELECT bomb FROM $tablename WHERE id=:strID");
$stmt->bindParam(':strID', $id);
$stmt->execute();
?>

PHP Manaual refernce: http://php.net/manual/en/pdo.prepared-statements.php

+2
source

usually this level of database abstraction is based on a prepared statement to handle the place owner function. The given function of the RDBM operator compiles the query, I do not think that it is possible to prepare the query if the table is not specified.

You must use the descent function of your library and include the table name in the query.

example:

$tablename = escapement_function($strTable);
Database->prepare("SELECT bomb FROM {$tablename} WHERE id=?")
        ->execute($strID);
+1
source

All Articles