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条)

报告相同问题?

悬赏问题

  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线