bonaca bonaca - 5 months ago 7
PHP Question

How to use a variable instead of table name?

This works fine:

$stmt = $db->prepare('SELECT id, title, content FROM table_01 WHERE id = :id');
$stmt->execute(array(':id' => $_GET['id']));
$row = $stmt->fetch();


but this gives an error:

$table = "table_01";
$stmt = $db->prepare('SELECT id, title, content FROM'.$table.'WHERE id = :id');

Answer

You can do it in two ways:-

$table = "table_01";
$stmt = $db->prepare('SELECT id, title, content FROM '.$table.' WHERE id = :id'); (adding space before and after table in your code)

OR

 $table = "table_01";
 $stmt = $db->prepare("SELECT id, title, content FROM  $table WHERE id = :id"); (adding space before and after table and use double quotes  in your code)