douyue2313 2018-03-04 12:54
浏览 48
已采纳

在Select SQL查询中使用PHP变量,它返回Error [duplicate]

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);
</div>
  • 写回答

1条回答 默认 最新

  • doukongyong44772 2018-03-04 12:57
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)