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.

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

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元