1

I am trying to make a simple search-function that's going to select and show everything, from a column.

if(isset($_GET["search"]) && ($_POST["filter"] != "all")) {
    $filter = $_POST["filter"];
    $sql = "SELECT :table FROM johnson LIMIT 0,30";
    $stmt = $dbh->prepare($sql);
    $stmt->bindValue(":table", $filter, PDO::PARAM_STR);
    $stmt->execute();
} 

This snippet seems to work just as it should.

Then I'm trying to display the data:

<?php } else if($filter != "all") { ?>

<tr>
    <td><?php echo $row["$filter"]; ?></td>
</tr>

<?php 
}

$filter corresponds with the proper database column, like if $filter == 'email', it should be SELECT email FROM johnson.

The result? After querying the database, it just loops the column name like:

email
email
email
email

And not foo@bar.com, etc. Whats wrong? Using PDO::FETCH_ASSOC.

It even works when hardcoded, and not using :table.

Bojangles
  • 99,427
  • 50
  • 170
  • 208
DreamHawk
  • 785
  • 2
  • 9
  • 20

1 Answers1

1

I am afraid that is a limitation of prepared statements.

If you bind a variable it will effectively be seen on the other end as a string - that's why your result is always "email" instead of the email coloumn.
The same reason is behind why you cannot use a variable for the order by field.

Community
  • 1
  • 1
Maerlyn
  • 33,687
  • 18
  • 94
  • 85
  • So there's no workaround? i simply have to have 1 query for each column? like "SELECT email FROM...", "SELECT employee FROM..." and so forth? :/ – DreamHawk Dec 28 '11 at 11:14
  • 1
    @DreamHawk No, just list your columns like `SELECT email, foo, bar FROM table`. – Bojangles Dec 28 '11 at 11:15
  • Okay, i made a simple switch-case, switch($filter) - email -> SELECT email FROM..., And that worked! Thanks :) – DreamHawk Dec 28 '11 at 11:18