简体   繁体   中英

Can I create a MYSQL table using a PDO parameterized statement?

I wish to create a MySQL table using PHP and PDO. I also wish to parameterize the table name. I have already attempted to implement this and the code, with errors, is shown below.

class databaseaccess {

    public $hostname = 'localhost';
    public $username = 'root';
    public $password = 'root';
    private $db = null;
    public $rows;

    public function __construct() {
        try {
                $this->db = new PDO("mysql:host=$hostname;dbname=noteshareproject", $this->username, $this->password);
        }
        catch (PDOException $Exception) {
            throw new Exception("DB failed to connect ".$Exception->getMessage());
        }
    }

    public function writetable($title,$id){
        if ($this->db === null) throw new Exception("DB is not connected");
        //query works with `:title` however keeps the commas. Gotta find out what is wrong.
        $query = "CREATE TABLE noteshareproject.:title (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), username VARCHAR(20)) ENGINE=myISAM;";
        $statement = $this->db->prepare($query);
        $title = $title . $id;
        $title = (string) $title;
        $statement->bindValue(':title', $title, PDO::PARAM_STR);
        $statement->execute();
        print_r($statement->errorInfo());
        echo $title;

    }
}

The output of the above code is as follows:

Array
(
    [0] => 42000
    [1] => 1064
    [2] => 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 ''exampletablename'(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), username VARCHAR(20)) EN' at line >2
)
exampletablename

What have I done wrong in my MySQL syntax or PDO implementation?

You cannot use placeholders in prepared statements for identifiers (column/table/database/function names etc). You can only use them for values.

CREATE TABLE noteshareproject.:title
//                            ^^^^^^ this will not work

You will have to manually sanitise $title so it can be used directly in the string if you want to do this.

Note also that a DDL statement such as CREATE TABLE cannot be prepared, so there is no point in using prepare() . You might as well just use query() or exec() .

I do also wonder if the fact that you want to do this at all is an indicator of poor database design - it is unlikely that a requirement for multiple tables of identical structure is a proper way to store your information, although without knowing more about your application it is impossible to say for sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM