如何使用一个表项中的 id 连接另一个表项

我对 php 和 sql 很陌生,并且在创建 Web 应用程序时正在学习,所以我想知道这将如何实现,如果有的话,或者对于这类任务是否有更好的做法。


举个例子:假设我有一个有 2 个表的数据库,一个是作者,另一本书


author table

-----------

id | author

1 | jones

2 | jane


book table

----------

id | title | author

1 | Learning php | 1 <- i want this to reference the author from author table

2 | Foobar | 1

3 | How to give a proper high five | 2

我有一个表单,它从查询中获取作者姓名作为选择标签,当我提交表单时,我想将 id 分配为 book 表中作者的值


$authorQuery = mysqli_query($con, "SELECT * FROM author");


<form id="bookForm" action="books.php" method="POST">

<label for="title">Book Title</label>

        <input type="text" name="title">


<label for="author">Author</label>

        <select id="author" name="author">

                <?php

                    while($row = mysqli_fetch_array($authorQuery)) {            

                        //display as an array in a drop down list

                        echo '<option>' . $row['author'] . '</option>';

                            }

                ?>

</form>

我该怎么办?


肥皂起泡泡
浏览 209回答 2
2回答

郎朗坤

我会将选项值设为作者 ID,更改此设置echo '<option>' . $row['author'] . '</option>';对此echo '<option value="' . $row['id']. '">' . htmlspecialchars($row['author']) . '</option>';现在,当提交此表单时,在服务器上您将在$_POST['author']变量中收到作者的 id ,因此您可以使用 id 而不是作者的姓名进行更新查询。$query = "update book set author_id = ? where title = ?";$stmt = $con->prepare($query);$stmt->bind_param("is", $_POST['author'], $_POST['title']);$stmt->execute();建议:这个方案意味着你的关系是1:m(1个作者可以写很多书,但是1本书必须只有1个作者写),这是不正确的,因为很多书是由很多作者写的,所以你需要使用第三个连接表来表示多对多关系m:m默认情况下,MySQL 上的搜索不区分大小写,但是最好<select>为书籍创建 a而不是将书籍<input>的 ID 分配给<option>s 而不是键入标题(除非您有太多书籍无法放入选择中),因此,当您需要填写表格以将作者分配给一本书时,请确保避免在书名中出现任何拼写错误

精慕HU

最简单的方法是&nbsp; <?php&nbsp; $stmt = $conn->prepare("SELECT * from book")&nbsp; &nbsp; $stmt->execute();&nbsp; &nbsp; &nbsp;foreach($stmt as $row){&nbsp; &nbsp; $id = $row['author'];$stmt = $conn->prepare("SELECT * from author WHERE id='$id'")&nbsp; &nbsp; $stmt->execute();&nbsp; &nbsp; foreach($stmt as $row){&nbsp; &nbsp; $name = $row['author'];?><option value="<?php echo $name;?>"><?php echo $name;?></option>&nbsp; &nbsp; }&nbsp; &nbsp; }复杂方法是&nbsp; &nbsp; $stmt = $conn->prepare("SELECT *, book.author AS bookauthor FROM book LEFT JOIN author ON author.id=book.id");&nbsp; &nbsp; &nbsp; &nbsp; $stmt->execute();foreach ($stmt as $row) {?><option value="<?php echo $row['bookauthor'];?>"><?php echo $row['bookauthor'];?></option>}
打开App,查看更多内容
随时随地看视频慕课网APP