[英]SQL query dosnt know variables
我正在尝试使用一个简单的下拉列表来查询数据库中的某些表,其中列出了表的名称。 该查询只有一个记录结果,显示数据库中注册的最年轻机构的名称和年龄!
$table = $_GET['table'];
$query = "select max('$table'.est_year) as 'establish_year' from '$table' ";
我需要将表的名称作为变量发送到查询php文件。 当我将变量名放在查询语句中时,无论方法是GET还是POST两种方法,它都会产生错误:
“您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以获取在'.order)附近将'customers'作为'customer'使用的正确语法”
您将表名用单引号引起来,这不是有效的SQL(这是字符串的语法,而不是表名)。 您要么根本不包装名称,要么将其包装在反引号中(在美国键盘布局上,这就是TAB上方的键)。
您也不应引用别名established_year
:
select max(`$table`.est_year) as establish_year from `$table`
另外,您的代码容易受到SQL注入的攻击。 立即解决此问题!
在这种情况下,最适当的操作可能是根据白名单验证表名称:
if (!in_array($table, array('allowed_table_1', '...'))) {
die("Invalid table name");
}
单引号(') ,在mysql中,它表示字符串值。
SELECT *, 'table' FROM `table`;
所以你的查询应该是
$table = $_GET['table'];
$query = "select max($table.est_year) as 'establish_year' from $table ";
另请阅读旧文章, phpmyadmin sql撇号不起作用 。
同样,您的代码也容易受到SQL注入的攻击。 你可以用这样的东西
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$firstName = clean($_POST['firstName']);
$lastName = clean($_POST['lastName']);
.
.
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.