SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2012
    2 Post(s)
    0 Thread(s)

    Question which way to loop or new technique

    Dear all have you got any technique loop code look like this
    PHP Code:
            $handler=$this->prepare('SELECT :field FROM :table');
    $handler->execute(array( ':field' => $field':table' => $table 
    what i need is ':field' => $field, ':table' => $table pleas help
    Last edited by guido2004; Aug 19, 2012 at 23:45. Reason: got rid of double code tags

  2. #2
    SitePoint Enthusiast Atli's Avatar
    Join Date
    Feb 2009
    0 Post(s)
    0 Thread(s)
    That question doesn't really make any sense, but I can tell you that what you're doing in your code will never work.

    Placeholders in prepared statements are meant for values, not identifiers. They will never actually be a part of the query; they are passed to the database with the query and used after the query has been parsed. This is important to understand, because without a valid field definitions and a valid table name, the query won't parse correctly.

    If you need to construct a query based on variables, you'll need to do that the old fashioned way. You shouldn't really need to use prepared statements anyways, because under no circumstances should you be passing external variables into a query as an identifier without extensive validation and white-listing. In fact, you would do much better to use hard-coded values for the input, selected based on those variables

    Something along the lines of:
    PHP Code:
    function get_query_data() {
    $valid_tables = ["table1""table2""table3"];
    $valid_fields = ["field1""field2""field3""field4"];

        if (!
    in_array($_GET["table"], $valid_tables)) {
            throw new 
    Exception("Invalid table name passed!");
        if (!
    in_array($_GET["field"], $valid_fields)) {
            throw new 
    Exception("Invalid field name passed!");
        return [
    "table" => $_GET["table"], "field" => $_GET["field"]];

    try {
    $data get_query_data();
    $sql "SELECT %s FROM %s";
    $sql sprintf($sql$data["field"], $data["table"]);
    catch (
    Exception $e) {
    trigger_error($e->getMessage(), E_USER_ERROR);


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts