在mysql查询中使用变量作为列名 [英] Using a variable as the column name in a mysql query
问题描述
我正在试图解决这个问题
I'm trying to turn this:
"SELECT username FROM $table WHERE username='$newName'"
对此:
"SELECT $column FROM $table WHERE $column='$newName'"
但是当我在其上使用or die()
时,我收到一条错误消息,指出WHERE username='someNameHere'
附近的语法不正确.假设这是错误的,替换列名称的正确方法是什么?
But when I use or die()
on it, I get an error saying that there is incorrect syntax near WHERE username='someNameHere'
. What is the correct way to substitute the column name, assuming that's what's wrong?
编辑:代码就是这样.这些值应该正确,因为我看不到错误中的任何拼写错误.
Code is just this. The values should be correct as I don't see any mispellings in the error.
$sql = "SELECT $column FROM $table WHERE $column='$newName'";
$result = mysql_query($sql) or die( mysql_error());
推荐答案
像这样进行查询
$sql = "SELECT ".$column." FROM ".$table." WHERE ".$column."='".$newName."'"
顺便说一句,这是SQLinjection易受攻击的代码.在查询中使用变量之前,应检查它们.另外,您应该开始使用 mysqli 和
BTW this is SQLinjection vulnerable code. You should check the variables before using them in query. Also you should start using mysqli and prepared statements
这篇关于在mysql查询中使用变量作为列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!