0

I try to make and INSERT INTO with a variable for table but i can't make it work.

here is my code :

    $tb = "mytable" ;
$req = $bdd->prepare('INSERT INTO :tb (users, info)
                VALUES(:users, :info)')
            or exit(print_r($req->errorInfo()));
$req->execute(array(
            'tb' => $tb,    
            'users' => $name,
            'info' => $website,
            ));

I get this message : 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 ''mytable' (users, info' at line 1 )

I really don't know what i should change...

thanks a lot

bernardo
  • 381
  • 3
  • 9

1 Answers1

0

PDO can accept data as parameters, not table names or column names.

Use something like this:

$tb = "mytable" ;
$req = $bdd->prepare('INSERT INTO `' . $tb . '` (users, info)
        VALUES(:users, :info)')
    or exit(print_r($req->errorInfo()));
$req->execute([
    'tb' => $tb,    
    'users' => $name,
    'info' => $website,
]);
Nick
  • 9,735
  • 7
  • 59
  • 89