[英]How to prefix / suffix column names in a MySQL query?
我将用户类型(卖方或买方)作为$_SESSION['user_type']
存储在我的会话变量之一中。
我的一些选择/插入/更新查询需要以seller_id
或buyer_id
为名称的列。
我想知道是否有办法在查询中将_id
后缀添加到$_SESSION['user_type']
。
例如:如果我想从我的order
表中选择所有的列,其中buyer_id
等于7
,我的查询应该是这样的:
SELECT *
FROM `order`
WHERE ( $_SESSION['user_type'] + "_id" ) = '7'
注意:我知道我可以使用一个变量并生成相应的列名,但是想知道这是否可以在没有任何额外变量的情况下实现。
只需将查询连接为字符串然后使用它。
$query = "SELECT *
FROM `order`
WHERE " . $_SESSION['user_type'] . "_id = '7'";
但是请确保您不会以这种方式包含来自用户输入的任何内容。
如果我看到可能有 SQL 注入的旧帖子,我会发帖...
如果您必须在查询中使用变量的值,那么
使用白名单- 请!
例子:
// even if its a session stored on your server and the values set by your self ...
// do NOT trust it and handle it as any other value from any other varible.
// example input:
// $_SESSION['user_type'] = 'seller';
// define the map of valid session user types and column relations (hardcoded)
$columnMap = [
// user_type => column name
'buyer' => 'buyer_id',
'seller' => 'seller_id',
];
// check if you got a valid session type (if you find it on the white list)
if (!isset($columnMap[$_SESSION['user_type']])) {
throw new \InvalidArgumentException("Invalid session[user_type].");
}
// use the value from the white list
$columnName = $columnMap[$_SESSION['user_type']];
// create proper query
$query = "SELECT * FROM `order` WHERE `{$columnName}` = :id;";
// Note:
// "SELECT * FROM `order` WHERE
// `{$columnName}` -- use ` to enclose the column name
// = :id -- use placeholder (prepared statements f.e. PHP PDO)
// ; -- finish statement with semicolon
// "
PHP PDO: https : //www.php.net/manual/de/pdo.prepared-statements.php
为什么?
因为代码可能会随着时间的推移而改变,并且您会从 POST 或 GET 请求中获得(即)user_type。
还是——为什么?
去搜索“SQL 注入”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.