0

(php 7.4)

Here is what this code should do:

Let the user pick a table, a column, then pick a search term. Return results.

What it actually does: nothing. It seems to not actually bind any variables into the statement. The reason I use a prepared statement is to prevent SQL-injection.

$table = $_GET["t"];
$column = $_GET["c"];
$term = $_GET["s"];

echo "t: '$table' ";
echo "c: '$column' ";
echo "s: '$term' ";

$stmt = $pdo->prepare("SELECT `:col` FROM `:table` WHERE `:col` LIKE ':term%';")
$stmt->execute([
  ':col'   => $column,
  ':table' => $table,
  ':term'  => $term
]);

$results = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

echo json_encode($results);

Sample output:

t: 'testtable' c: 'testcol' s: 'hello wo'

Fatal error: Uncaught PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dvwatch.?' doesn't exist in /srv/http/autocomplete.php:26 Stack trace: #0 /srv/http/autocomplete.php(45): get_autocompletions() #1 {main} thrown in /srv/http/autocomplete.php on line 26

As you can see, it put [database_name].? instead of [db_name].testtable

Yes, the table exists. Yes it's populated.

USB_S0lderer
  • 160
  • 1
  • 6
  • 1
    Does this answer your question? [Can PHP PDO Statements accept the table or column name as parameter?](https://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-or-column-name-as-parameter) – waterloomatt Nov 18 '20 at 17:54
  • 1
    You also need to check how to use a bind value with LIKE - some bits from https://stackoverflow.com/questions/22154246/pdo-prepare-with-bindvalue-and-like should help. – Nigel Ren Nov 18 '20 at 17:56

0 Answers0