0

I was wondering if it's possible to define tables and columns names and use them in different sql queries in a php script.

I tried some combinations like:

define("USERS_TABLE", "users");
define("COLUMN_NAME", "username");

function getUserName()
{
    $dbh = new DBHandler();    
    if ($dbh->getInstance() === null) {
        die("No database connection");
    }
    try {
        $sql = "SELECT".COLUMN_NAME."FROM".USERS_TABLE"where id=1";
        $stmt = $dbh->getInstance()->prepare($sql);
        $stmt->execute();
        return $number_of_rows = $stmt->fetchColumn();
    }    
}

I also tried:

try {
    $sql = "SELECT :column FROM :table where id=1";
    $stmt = $dbh->getInstance()->prepare($sql);
    $stmt->bindParam(':column', COLUMN_NAME, PDO::PARAM_STR);
    $stmt->bindParam(':table', USERS_TABLE, PDO::PARAM_STR);
    $stmt->execute();
    return $number_of_rows = $stmt->fetchColumn();
}

And:

define("USERS_TABLE", "users");
define("COLUMN_NAME", "username");

$tablename= USERS_TABLE;
$columnname = COLUMN_NAME;

function getUserName() use ($tablename,$columnname)
{
    try {
        $sql = "SELECT :column FROM :table where id=1";
        $stmt = $dbh->getInstance()->prepare($sql);
        $stmt->bindParam(':column', $columnname, PDO::PARAM_STR);
        $stmt->bindParam(':table', $tablename, PDO::PARAM_STR);
        $stmt->execute();
        return $number_of_rows = $stmt->fetchColumn();
    } 
} 

but without any success. Maybe it's not possible to do such kind of things? Thanks

  • 4
    Probably, sure. However you need to space out your query, since that could translate as `SELECTusernameFROMusersWHERE id=1` resulting in a syntax error. You also have a missing concatenate. – Funk Forty Niner Apr 06 '16 at 16:25
  • ok I will try, for the moment thank you :) – user2431729 Apr 06 '16 at 16:44
  • Unfortunately the corrections were not enough, I thought that maybe I could have used `bindParam` but it doesn't work.. – user2431729 Apr 06 '16 at 17:23
  • 1
    that's because in your newly posted code, you can't bind tables and/or columns and using http://php.net/manual/en/pdo.error-handling.php would have told you about another syntax error for it. See http://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-or-column-name-as-parameter about why you can't. – Funk Forty Niner Apr 06 '16 at 17:27

0 Answers0