Php 如何在MySQL查询中为列名添加前缀/后缀?

Php 如何在MySQL查询中为列名添加前缀/后缀?,php,mysql,sql,string,session,Php,Mysql,Sql,String,Session,我正在将用户类型(卖方或买方)存储在会话变量之一中,作为$\u session['user\u type'] 我的一些select/insert/update查询要求列的名称为seller\u id或buyer\u id 我想知道是否有一种方法可以在我的查询中将\u id后缀添加到$\u会话['user\u type'] 例如:如果我想从我的order表中选择buyer\u id等于7的所有列,我的查询应该如下所示: SELECT * FROM `order` WHERE ( $_SESSION

我正在将用户类型(卖方或买方)存储在会话变量之一中,作为
$\u session['user\u type']

我的一些select/insert/update查询要求列的名称为
seller\u id
buyer\u id

我想知道是否有一种方法可以在我的查询中将
\u id
后缀添加到
$\u会话['user\u type']

例如:如果我想从我的
order
表中选择
buyer\u 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:

为什么?

因为代码可能会随着时间的推移而变化,您可以从POST或get请求中获得(即)用户类型

还是-为什么


去搜索“SQL注入”。

你只需要构建一个字符串,就像其他任何字符串一样,我们不能在查询本身中生成字符串吗?查询是一个字符串哦,你有其他东西的错误,讨厌这个:-)@JonathanM当然会的。刚从SQL开始。:)