dpi74187 2019-01-02 07:28
浏览 26
已采纳

如何在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.

  • 写回答

1条回答 默认 最新

  • douzaoqu4447 2019-01-02 07:46
    关注

    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;
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?