我有一个表,显示书籍的元组和有关它们的数据。每行还有一个单选按钮。这个想法是,用户选择该按钮来表明他们想要订购该书。
function displayAllBooks(){
$dbhost = 'localhost:3306';
$dbuser = 'root';
$conn = mysqli_connect($dbhost, $dbuser);
//sql statement to use the database
$sql = 'use BookStore';
mysqli_query($conn, $sql);
$sql = 'SELECT * FROM Author, Books, Written_By, Book_Categories, Assigned_To '
. 'WHERE Author.Author_ID = Written_By.Author_ID'
. ' AND Books.ISBN = Written_By.ISBN'
. ' AND Books.ISBN = Assigned_To.ISBN'
. ' AND Assigned_To.Cat_Code = Book_Categories.Cat_Code'
. ' ORDER BY ALname ASC';
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
echo '<form action = "customerDashboard.php" method = "post">';
echo 'First name:
<input type= "text" name ="CFname"<br>
Last name:
<input type= "text" name ="CLname"<br>';
echo '<p style="text-align:center"><b> All Books </b></p>';
echo '<table class="center">'
. '<tr>'
. '<th>Order</th>'
. '<th>Title</th>'
. '<th>Price</th>'
. '<th>Author</th>'
. '<th>Publication Date</th>'
. '<th>User Review</th>'
. '<th>Category</th>'
. '</tr>';
if (mysqli_num_rows($result) > 0) {
$bookCt = 0;
//mysqli_fetch_assoc associates an array with the results
while ($row) {
$retTitle = $row["Title"];
$retPrice = $row["Price"];
$retALname = $row["ALname"];
$retPubDate = $row["Publication_Date"];
$retReview = $row["User_Reviews"];
$retCat = $row["Cat_Desc"];
//fetch ISBN for each book, for use with the radio buttons to
//place orders
$sql = 'SELECT ISBN from Books WHERE Title="'.$retTitle .'"';
$resultISBN = mysqli_query($conn, $sql);
$rowISBN = mysqli_fetch_assoc($resultISBN);
$currISBN = $rowISBN["ISBN"];
echo"<tr>";
echo '<td><input type="radio" name="'.$currISBN.'"></td>';
echo "<td> $retTitle </td>";
echo "<td> $retPrice </td>";
echo "<td> $retALname </td>";
echo "<td> $retPubDate </td>";
echo "<td> $retReview </td>";
echo "<td> $retCat </td>";
echo "</tr>";
$row = mysqli_fetch_assoc($result);
}
}
else {
echo "0 results";
}
echo "</table>";
echo '<input type="submit" name="placeOrder" value="Order Selected Book">';
echo '</form>';
我一直在尝试类似 onselect="将按钮名称加载到 session 变量中"之类的方法,但我一直无法实现它。
每个单选按钮都有一个名称值,该名称值是当前放入表中的图书的 ISBN(主键)。我希望能够选择一个单选按钮,将该 ISBN 存储在 session 或全局变量中,并将该特定 ISBN 用于另一个方法 placeOrder()。选中单选按钮后,用户输入他们的名字和姓氏,然后按“订购所选书籍”,这将重新加载页面并通过以下方式触发 placeOrder() 函数:
else if(isset($_POST["placeOrder"])){
//for placing orders on a single book
placeOrder();
}
它出现在 PHP 部分的开头,与其他函数调用一起。
我对 PHP 和 HTML 还很陌生,所以如果答案很明显,请原谅我。如果单选按钮名称是明确的,我可以这样做,但由于它随着每一行而变化,我无法弄清楚。
主要思想:如何捕获所选单选按钮对应的信息,以便我可以在另一个函数中使用所述信息?
答案不必涉及 session 或全局变量,我们将不胜感激。
最佳答案
您可以用一个数组来表示单选按钮,并以 isbn 作为索引
echo '<td><input type="radio" name="books['.$currISBN.']"></td>';
然后在服务器端循环它
foreach ($_POST['books'] as $isbn => $on){
// do something with $isbn
}
关于php - 当单选按钮的名称是变量时,如何从单选按钮获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40819099/