2

我正在尝试将数据库中的每个列名存储到它自己的 $_SESSION 中。例如,假设我的列名是 column_one、column_two、column_three、column_four 和 column_five。我希望将它们存储在 $_SESSION 中,例如 $_SESSION['column_one']、$_SESSION['column_two'] 等。我试图循环执行此操作,但没有成功。我将如何设置循环来实现这一点?

$query = "SELECT * FROM table WHERE user_id = $id";
$result = mysqli_query($dbc, $query);
$num = mysqli_num_rows($result);

if ($num == 1) {

    //User was found
    while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
        $_SESSION['user_id'] = $row['user_id'];
    }

}
4

3 回答 3

3

你能试试这个:

$id = mysqli_real_escape_string($dbc,$id);
$query = "SELECT * FROM table WHERE user_id = $id";
$result = mysqli_query($dbc, $query);
$num= mysqli_num_rows(result);
if ($num == 1) {
    $row = mysqli_fetch_assoc($result);
    $_SESSION['UserData'] = $row;
}else{
//handle error or user not found
}

echo '<pre>';
print_r($_SESSION['UserData']);
echo '</pre>';

您没有必要使用 while 或另一个循环,所以只有一行

于 2013-08-10T01:15:34.343 回答
2

像这样的东西应该工作:

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    foreach($row as $column => $value) {
        $_SESSION[$column] = $value;
    }
}

针对 SQL 注入的额外建议,以下两行:

$id = mysqli_real_escape_string($dbc, $id);
$query = "SELECT * FROM table WHERE user_id = '$id'";

更新:

感谢 EmilioGort 指出mysqli_real_escape_string. 请参阅mysqli_real_escape_string文档。

于 2013-08-10T01:15:12.080 回答
0

While the other answers proposed a way to do, I'd strongly propose to not do this at all. Why?

First of all $row contains all details of the user in a well defined array form. It is generally good to keep this structure well prepared.

More important: Flattening $row might force name clashes like so:

Suppose $row has a property userName and somewhere else in your application you eventually set

$_SESSION[ 'userName' ] = $newUserName;

The new assignment to $_SESSION[ 'userName' ] might unintentionally change the property saved during the login process.

You might argue "Right now, my code doesn't use userName in $_SESSION'. Right! Unfortunately, you might use just this name for something else many month later on...

A better solution

I'd save the user detail like this:

$_SESSION[ 'sys$userDetails' ] = $row;

Imagine the prefix sys$ as being an indicator for framework generated properties of your session.

Thus, business logic related session data shouldn't have the sys$ prefix.

于 2013-08-10T01:47:47.683 回答