0

I want to CREATE a table using using PDO prepared statments. The problem is that bindValue adds '' around the binded value. I don't understand why this happens. How can I avoid this so that my table name is set as users and not 'users'? Thanks.

Code:

<?php

$table = "users";

try {

  $db = new PDO("mysql:host=localhost;dbname=test", "root", "");
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $sql = "CREATE TABLE `:table` (id INT(11) AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL)";
  $stmt = $db->prepare($sql);
  $stmt->bindValue(':table', $table);
  $stmt->execute();

} catch(PDOException $e) {

  echo $e->getMessage();

}

?>

Here is the result in phpmyadmin:

enter image description here

guizo
  • 2,594
  • 19
  • 26
  • 2
    You can't bind table names and column names. You'll need to pass it in directly, though you should verify it first if it's coming from a form. – aynber Mar 13 '17 at 17:51
  • If I can`t use PDO prepared statments with table names and column names how can I avoid SQL injections when the table name comes from $_POST? – guizo Mar 16 '17 at 18:14
  • Create a list of table names and column names, or grab it from the database. Verify that the value coming from the form matches what already exists before using it. – aynber Mar 16 '17 at 18:18

0 Answers0