将字段名称作为变量传递

将字段名称作为变量传递

本文介绍了PDO-将字段名称作为变量传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是将代码从mysql_query样式命令迁移到PDO样式,所以遇到了问题.旧代码看起来像这样:

I'm just migrating my code from mysql_query style commands to PDO style and I ran into a problem. THe old code looked like this :

$query_list_menu = "SELECT ".$_GET['section_name']." from myl_menu_hide_show WHERE id='".$_GET['id']."'";

更新后的代码如下所示.显然它不起作用.我在$_GET['section_name']中存储一个字符串,该字符串表示数据库中的字段名称.但是我认为将其作为变量传递时存在问题.以下代码有效吗?谢谢.

And the updated code looks like below. Apparently it's not working. I store in $_GET['section_name'] a string that represents a field name from the database. But I think there is a problem when I pass it as a variable. Is the below code valid ? Thanks.

$query_list_menu = "SELECT :section_name from myl_menu_hide_show WHERE id=:id";
$result_list_menu = $db->prepare($query_list_menu);
$result_list_menu->bindValue(':section_name', $_GET['section_name'] , PDO::PARAM_STR);
$result_list_menu->bindValue(':id', $_GET['id'] , PDO::PARAM_INT);
$result_list_menu->execute();

推荐答案

如果$_GET['section_name']包含列名,则您的查询应为:

If $_GET['section_name'] contains a column name, your query should be:

$query_list_menu = "SELECT " . $_GET['section_name'] . " from myl_menu_hide_show WHERE id=:id";

给予:

$query_list_menu = "SELECT :section_name from myl_menu_hide_show WHERE id=:id";
$result_list_menu = $db->prepare($query_list_menu);
$result_list_menu->bindValue(':id', $_GET['id'] , PDO::PARAM_INT);
$result_list_menu->execute();

原因是您希望将列的实际名称包含在查询中-您已将其更改为参数,这实际上没有多大意义.

The reason is that you want the actual name of the column to be in the query - you'd changed it to be a parameter, which doesn't really make much sense.

我还要补充一点,直接使用$_GET['section_name']这样会带来巨大的安全风险,因为它允许进行SQL注入.我建议您在构建和执行查询之前,通过对列列表进行检查来验证$_GET['section_name']的值.

I'll also add that using $_GET['section_name'] directly like this is a massive security risk as it allows for SQL injection. I suggest that you validate the value of $_GET['section_name'] by checking it against a list of columns before building and executing the query.

这篇关于PDO-将字段名称作为变量传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 22:26