在mysql查询中使用变量作为列名 [英] Using a variable as the column name in a mysql query

查看:1212
本文介绍了在mysql查询中使用变量作为列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图解决这个问题

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆