1

I am new to PHP and MySQL and I am trying to use PHP Variable as name of table. But when I do that it returns :

SQL Error: 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 '321321' at line 1

My code is :

$dbname = "321321";
require_once('authenticate.php');
$ownerID =  $_SESSION["accNumber"];
if($dbname != $ownerID){
    header('Location: login.php');
}


$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = '***'; // Password
$db_name = 'test_database'; // Database Name

$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}



$sql = 'SELECT * FROM '.$dbname.'';
$query = mysqli_query($conn, $sql);
  • `321321` is not a valid database name – Flying Mar 04 '18 at 12:56
  • 2
    You probably mean to use `$db_name`, not `$dbname` – ishegg Mar 04 '18 at 12:57
  • @ishegg There are two variables `$dbname` and `$db_name` in the question. – Syscall Mar 04 '18 at 12:58
  • @Syscall I know, and only the second one looks like the one he wants to use (it’s grouped with the other, has a comment explaining what it is, etc) – ishegg Mar 04 '18 at 12:59
  • @ishegg Yes, but the OP already used `$db_name` in the connection, so no point in an additional `use` statement, right? – Racil Hilan Mar 04 '18 at 13:02
  • @RacilHilan I just now realized this is about the database name, not the table name. Got confused. I think OP might have those confused as well... if he only came back and replied :/ – ishegg Mar 04 '18 at 13:05

1 Answers1

0

You should add backticks ` around your table name, because it doesn't begin by a letter :

$sql = 'SELECT * FROM `'.$dbname.'`';

As pointed by @RacilHilan (see comment below), it would be better to rename the table to avoid this kind of confusions.

Syscall
  • 19,327
  • 10
  • 37
  • 52