dqg2269 2015-11-30 13:18
浏览 121
已采纳

通过PHP创建动态按钮

I am trying to query mysql via PHP to get a list of class names from a table. I then want the user to click on one of these class names to be redirected to a page which displays the class roster for whatever class was clicked on. The rosters are generated on-the-fly from another table in the database, right now I'd like to just save the class name as a session variable, then have the roster.php page use that variable to query for the correct roster.

ex.)

class a -click-> roster.php

-> echo (// roster 'a' as <ol> from table);

class b -click-> roster.php

-> echo (// roster 'b' as <ol> from table);

class a -click-> roster.php

-> echo (// roster 'c' as <ol> from table);

I understand how to query and how to echo out html lists through a php page, but I'm not sure how I would generate buttons for the class names, then have the webpage track which button is clicked on.

Here is the code I have written to generate the rosters from the database.

$sql = "SELECT firstname, lastname FROM student_Data WHERE classs =" . $_SESSION['classname'];
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     // output data of each row
     echo("<div id=\"list1\">")
     while($row = $result->fetch_assoc()) {
         echo ("<li><h4 class=\"list-group-item-heading\">". $row["firstname"]. " " . $row["lastname"] . "</h4></li>");
     }
     echo("</div>");
} else {
     echo ("");
}

Side note: This is a personal project so I rather produce quick code over efficient code. Which is why I am OK with session vars.

  • 写回答

2条回答 默认 最新

  • dongshi1207 2015-11-30 13:41
    关注

    You can output a list of class links in pretty much the exact same way you're outputting a list of students. Assuming you have a database query in your previous page for the classes, it might look something like this:

    while($row = $result->fetch_assoc()) {
        echo ("<a href=\"class.php?id=" . $row["id"] . "\">" . $row["name"] . "</a>");
    }
    

    So the resulting links would look something like this:

    <a href="class.php?id=1">Class A</a>
    <a href="class.php?id=2">Class B</a>
    <a href="class.php?id=3">Class C</a>
    

    Then in your next page, you can get the identifier from the query string with $_GET["id"]. Note of course that this value can be changed by the user. So you do not want to use it directly in a SQL query as you currently do with your session value. (Which you shouldn't be doing either, really.) Instead, use a prepared statement and bind this as a value instead of executing it as code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能