문제

I want to use this method to get array of keys (primary, foreign, ...) from specified table:

public function getTableKeys($table){
    //OBTAIN TABLE KEYS
    try {
        $conn = $this->db->_pdo;    
        $conn->beginTransaction();

        $query = $this->db->_pdo->prepare('SHOW KEYS FROM :table');
        $query->bindParam(':table', $table, PDO::PARAM_STR);
        $query->execute();
        $keys = $query->fetchAll(PDO::FETCH_ASSOC);

        $conn->commit();
        return $keys;
    }catch (Exception $e) {
        $conn->rollback();
        echo 'Caught exception: ',  $e->getMessage(), "\n";
        return false;
    }
}

The problem is, there is an error thrown:

Caught exception: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ps_customer'' at line 1

Now if I run SQL manually in PHPMyAdmin, it successfully returns a set of keys. The problem is that it has to be in following format:

SHOW KEYS FROM ps_customers

not in this format (with quotes):

SHOW KEYS FROM "ps_customers"

My question is: How do I bindParam parameter that needs to be inserted into SQL without quotes but is in fast a string (use of PDO::PARAM_INT doesn't work).

Thanks for possible suggestions, guys.

도움이 되었습니까?

해결책

As Ben said you can't bind table names in prepared statements. You can sanitize the table name by whitelisting.

An array of allowed table names is used to ensure only those on the whitelist can be used.

$table = "table1";//Your table name
$allowed_tables = array('table1', 'table2');//Array of allowed tables to sanatise query
if (in_array($table, $allowed_tables)) {
    getTableKeys($table);
}   

The SQL SHOW KEYS FROM $table will only be queried if table1 is in list.

public function getTableKeys($table){
    //OBTAIN TABLE KEYS
    try {
        $conn = $this->db->_pdo;    
        $conn->beginTransaction();
        $query = $this->db->_pdo->prepare('SHOW KEYS FROM $table');
        $query->execute();
        $keys = $query->fetchAll(PDO::FETCH_ASSOC);

        $conn->commit();
        return $keys;
    }catch (Exception $e) {
        $conn->rollback();
        echo 'Caught exception: ',  $e->getMessage(), "\n";
        return false;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top