我希望使用数据作为单选按钮自动填充php / html表单,以允许用户从自己的记录中进行选择,并将其选择转换为另一种形式的可重用变量。

我已经从数据库获得了登录名和密码,并且可以使用适当的$variable创建会话user_id

然后,我陷入了正确的查询和html构造。我看了各种例子都没有用。

我的桌子如下

tableid Title           Author  published   colour  user_id ref_id
==================================================================
1       how to ski      pete    2014        red 2   1
2       how to cook     jones   2015        white   4       2
3       how to drive    smith   2012        yellow  2       3
4       how to cook     jones   2015        white   4       2
5       how to drive    smith   2012        yellow  4       3


我已经创建了基本查询来提取数据,但是正在努力使它显示为单选按钮的单选按钮。

$queryOrders2="SELECT * FROM books WHERE user_id=$user_id";
$resultOrders2=mysql_query($queryOrders2);
$row = mysql_fetch_assoc($resultOrders2);
print_r(mysql_fetch_assoc($resultOrders2));
$Title = $row["Title"];
$Author  = $row["Author"];
$published = $row["published"];
$colour = $row["colour"];`


然后,我尝试转换为单选按钮以允许选择单个记录

<form action="display-selections.php" method="POST">
<input class="radio_style" id="Title" name="Title" type="radio" value="Title">
<input class="radio_style" id="Author" name="Author" type="radio" value="Author">
<input class="radio_style" id="published" name="published" type="radio" value="published">
<input class="radio_style" id="user_id" name="user_id" type="radio" value="user_id">
<input name="submitted" type="submit" value="Submit">
</form>


但是代码是无效的,因为我是PHP的新手,现在仍然在学习。我感到很困惑,似乎有太多的例子以某种方式无法实现。

我已经尝试了许多不同的语法,但我一直在努力让自己了解如何允许用户以可选格式从mysql中选择数据。

任何在正确方向上的帮助或推动都会很棒。

最佳答案

首先,请不要使用MYSQL_ *函数。请改用PDO或MySQLi。参见:Why shouldn't I use mysql_* functions in PHP?

现在,一个工作示例:

HTML表单以选择要显示的列:

<!DOCTYPE html>
<html>
<head>
    <title>Form example</title>
</head>
<body>
    <form action="process.php" method="post">
        Choose columns (no selection = all columns) :
        <input type="checkbox" name="title" value="1"> Title
        <input type="checkbox" name="author" value="1"> Author
        <input type="checkbox" name="published" value="1"> Published
        <input type="checkbox" name="user_id" value="1"> User ID
        <input type="submit" value="submit">
    </form>
</body>
</html>


PHP文件的开头,用于处理复选框并相应地构建请求:

<?php

$fields = array();

foreach($_POST as $label => $value) {
    array_push($fields, "`" . $label . "`");
}

if(count($fields) > 0) {
    $field_list = implode(",", $fields);
} else {
    $field_list = "*";
}

echo $query = "SELECT " . $field_list . " FROM `table` WHERE condition";

//send query, retrieve and show data :)

?>

10-07 19:15
查看更多