-1

I'm storing the user type (seller or buyer) in one of my session variables as $_SESSION['user_type'].

Some of my select / insert / update queries require the columns by the name of seller_id or buyer_id.

I want to know if there's a way by which I can add the _id suffix to $_SESSION['user_type'] in my queries.

For example: If I want to select all the columns from my order table where buyer_id is equal to 7, my query should look something like this:

SELECT *
FROM `order`
WHERE ( $_SESSION['user_type'] + "_id" ) = '7'

Note: I know I can use a variable and generate the corresponding column name, but was wondering whether this is possible without any extra variable.

Nikunj Madhogaria
  • 2,139
  • 2
  • 23
  • 40

2 Answers2

1

Just concatenate query as string and use it then.

$query = "SELECT *
    FROM `order`
    WHERE " . $_SESSION['user_type'] . "_id = '7'";

But make sure that you'll not include anything from user input in such way.

Elon Than
  • 9,603
  • 4
  • 27
  • 37
0

If i see old post with possible SQL-Injections i have post ...

If you have to use the value of a variable in a query then

use a whitelist - Please!

Example:

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

Why?

Because code may change over years and you get the (i.e.) user_type from a POST or GET request.

Still - why?

Go search for "SQL-Injections".

cottton
  • 1,522
  • 14
  • 29