简体   繁体   English

如何在php中的会话变量中存储数组值并在以后使用它

[英]how to store array values in session variable in php and use it for later

I want to store all the id's in the session variable to use it later我想将所有 id 存储在 session 变量中以供以后使用

<div class="" style="padding-top: auto;">

<?php  
$item_id= $_SESSION['id'];
$conn = mysqli_connect("localhost", "root", "", "store")or die($mysqli_error($conn));
$select_query = "SELECT  * from users_items where user_email='$email'";
$select_query_result = mysqli_query($conn, $select_query) or die(mysqli_error($conn));
?>
    <table class="table table-bordered ">
        <th >status</th>
        <?php while ($row = mysqli_fetch_array($select_query_result)) { ?>
            <th class="container-fluid"  style="float: right;"> <?php echo $row['id']; 
        ?>


        <?php } ?>
        </th>    
    </table>
</div>

Add the IDs to the array in the loop.将 ID 添加到循环中的数组。

<div class="" style="padding-top: auto;">

<?php  
$item_id= $_SESSION['id'];
$conn = mysqli_connect("localhost", "root", "", "store")or die($mysqli_error($conn));
$select_query = "SELECT  * from users_items where user_email='$email'";
$select_query_result = mysqli_query($conn, $select_query) or die(mysqli_error($conn));
?>
    <table class="table table-bordered ">
        <tr><th >status</th></tr>
        <?php while ($row = mysqli_fetch_array($select_query_result)) { ?>
            <tr><td class="container-fluid"  style="float: right;"> <?php echo $row['id']; ?> </td></tr>
        <?php 
            $item_id[] = $row['id'];
        } ?> 
    </table>
</div>
<?php 
$_SESSION['id'] = $item_id;

Also, you need to put <tr>...</tr> around each row in the table, and the data should be in <td> rather than <th> .此外,您需要将<tr>...</tr>放在表中的每一行周围,并且数据应该在<td>而不是<th>

You should be using prepared statements.您应该使用准备好的语句。 You can then use array_column() to filter out id from the array of rows returned from DB.然后,您可以使用array_column()从 DB 返回的行数组中过滤掉 id。

<div class="" style="padding-top: auto;">

<?php
$item_id = $_SESSION['id'];

// enable mysqli errors
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli("localhost", "root", "", "store");
$mysqli->set_charset('utf8mb4'); // set proper connection charset

// prepare -> bind -> execute
$stmt = $conn->prepare('SELECT  * from users_items where user_email=?');
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result()->fetch_all(); // Fetch all rows into an array
$_SESSION['array_of_ids'] = array_column($result, 'id'); // filter out a single column and save into session
?>
    <table class="table table-bordered ">
        <th >status</th>
        <?php foreach($result as $row) { ?>
            <th class="container-fluid"  style="float: right;"> <?php echo $row['id']; ?>


        <?php } ?>
        </th>    
    </table>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM