如何在php中设置从数据库中获取的项目的会话[关闭]

如何在php中设置从数据库中获取的项目的会话[关闭]

问题描述:

I am very new to PHP. I have created a page that lists up some items fetched from the database. Each displayed item holds a button to know more about the item.

<?php include 'header.php'; ?>

<?php 

/*ESTABLISHING CONNECTION WITH DATABASE*/
    include 'connection.php'; 

/*FETCHING ALL DATA FROM DATABASE*/
    $sql = "SELECT id,shortname,name FROM table_item";
    $result = mysqli_query($conn,$sql);

?>

<!--SHOWING FETCHED DATA FROM DATABASE-->
    <div class="row">

    <?php while ( $row = mysqli_fetch_row($result) ) { ?>

    <div class="col-md-6">
        <div class="item-container">
            <h2><strong><?php echo $row[2]; ?></strong><?php echo ' (' . $row[1] . ')' ?></h2>
            <br><br>
            <button class="btn btn-primary">Click to know more</button>
        </div>
    </div>

    <?php } ?>

    </div>

<?php

/*RELEASING ALL DATABASE CONNECTIONS*/
    mysqli_free_result($result);
    mysqli_close($conn);

?>

<?php include 'footer.php'; ?>

The program should work like that when I click the Know More button, it should set a session with the Id of the item and it will redirect me to another page, where I can fetch other details related to the Id with the help of session.

I cannot understand how can I set the session with the Id of the item dynamically. Thanks in advance for the help.

Try this one:

In that file:

<div class="item-container">
    <h2><strong><?php echo $row[2]; ?></strong><?php echo ' (' . $row[1] . ')' ?></h2>
    <br>
    <br>
    <form action="to_another_page.php" method="post">
        <input type="hidden" name="id" value="<?php echo $row[0]; ?>">
        <button class="btn btn-primary">Click to know more</button>
    </form>
</div>

In another file:

<?php
if(isset($_POST['id'])) {
    $id = $_POST['id'];

    // Select table_item where id = id received
    $sql = "SELECT id, shortname, name FROM table_item WHERE id =" . $id;
    $result = mysqli_query($conn,$sql);

    // Set session variable named id with value id received
    $_SESSION["id"] = $id;
}
?>