fwoelffel
fwoelffel

Reputation: 411

Prepared sql request INSERT INTO a variable table

I'm trying to execute a prepared sql request wich should insert values into a variable table

This code will be more explicite than me :

$req = $db->prepare("INSERT INTO ? 
                    (    `id`, 
                         `parent_id`, 
                         `position`, 
                         `left`, 
                         `right`, 
                         `level`, 
                         `title`, 
                         `type`, 
                         `content`   ) 
                    VALUES (NULL, 
                         '2', 
                         'last', 
                         '3', 
                         '10', 
                         '2', 
                         ?, 
                         'default', ?);");

$req->execute(array($_SESSION["user_id"], $result["title"], $result["content"]));

All variables are set, I checked that with some echo. Isn't it possible to "INSERT INTO" a variable ?

(Each user has its own table named by its unique id, that's why I can't directly write the table name in the query)

Upvotes: 0

Views: 267

Answers (2)

andrewsi
andrewsi

Reputation: 10732

You can't use a named parameter for a table name; if you want to do that, you'll have to include the name in your SQL directly:

INSERT INTO $tablename (....

However - that's still open to SQL injection attacks.

If you want to store data like that, I'd put everything into a single table, and just add an extra field as an additional key.

Upvotes: 2

xdazz
xdazz

Reputation: 160883

No, you can't do this, you need to do like below.

$table = $_SESSION["user_id"];
$req = $db->prepare("INSERT INTO $table (`id`, `parent_id`, `position`, `left`, `right`, `level`, `title`, `type`, `content`) VALUES (NULL, '2', 'last', '3', '10', '2', ?, 'default', ?);");
$req->execute(array($result["title"], $result["content"]));

Upvotes: 0

Related Questions