如何在MySQL查询中添加列名的前缀/后缀


How to prefix / suffix column names in a MySQL query?

我将用户类型(卖方或买方)存储在我的会话变量之一$_SESSION['user_type']中。

我的一些select/insert/update查询要求列的名称为seller_idbuyer_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注入,我有post…

如果您必须在查询中使用变量的值,则

使用白名单 -拜托!

的例子:

// 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 - injection "