我试图在bootstrap数据表中显示数据库中的数据。问题是我有一个以上作者的书,所以我有一个数组用于名字,第二个用于姓氏。现在我无法在< td >
中显示它。
在两个数组中获取fnames和lnames并尝试以这种方式显示它还是有其他选择的好方法吗?
我的桌子和阵列:
这是我显示数据的代码:
$sql2 = "SELECT fname, lname FROM `books_has_authors` JOIN authors on books_has_authors.authors_id_author = authors.id_author
WHERE books_has_authors.books_book_id = '".$row["book_id"]."'";
$result2 = mysqli_query($conn, $sql2);
$authors_array = array();
$authors_array2 = array();
//Getting data names of all authors
while($row2 = mysqli_fetch_assoc($result2)){
$authors_array[] = $row2['fname'];
$authors_array2[] = $row2['lname'];
}
echo '<pre>';
print_r($authors_array);
print_r($authors_array2);
echo '</pre>';
echo '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["year"].'</td>
<td>
//Here I want display those names each in new line if possible
</td>
</tr>
';
答案 0 :(得分:1)
图书馆员通常会为这种形式的书籍列出多位作者。
David M Glover; David Dugan; Jeff Goldblum; James D Watson; Francis Crick;
例如,看一下这个商品。 https://www.worldcat.org/title/dna-the-secret-of-life/oclc/605305974
要执行此操作,您需要使用连接的名字和姓氏检索作者,可能使用如下查询:
SELECT CONCAT(fname, ' ',lname, ';') authorname FROM `books_has_authors` ...
然后,您可以将这些authorname
项放在一个表格单元格中。
或者,你可以这样做
SELECT GROUP_CONCAT(CONCAT(fname, ' ',lname, ';') SEPARATOR ' ') authornames
FROM `books_has_authors` ...
GROUP BY book
并获取可在表格单元格中使用的单个authornames
项目。
(请注意,作者在图书清单上的顺序不是由程序员或图书管理员决定的。它是由作者选择的。如果你在这个例子中列出了Crick博士的书,除了上一位作者,他会不高兴。)
答案 1 :(得分:0)
假设第一个和最后一个名字都被填充,你可以使用for循环来完成,基于数组值的数量:
for($x=0; $x < count($authors_array); $x++) {
echo '<p>'. $authors_array[$x] . ' ' . $authors_array2[$x] . '</p>';
}
...或者您可以更改select语句以连接名称,并仅为输出填充一个数组:
$sql2 = "SELECT CONCAT(fname, ' ', lname) AS 'fullname' FROM `books_has_authors` JOIN authors on books_has_authors.authors_id_author = authors.id_author WHERE books_has_authors.books_book_id = '".$row["book_id"]."'";
...
//Getting data names of all authors
while($row2 = mysqli_fetch_assoc($result2)){
$authors_array[] = $row2['fullname'];
}
...
//Here I want display those names each in new line if possible
for($x=0; $x < count($authors_array); $x++) {
echo '<p>'.$authors_array[$x].'</p>';
}
如果你已经回音,那么你可以关闭回声然后进行循环:
echo '.....
<td>';
//Here I want display those names each in new line if possible
for($x=0; $x < count($authors_array); $x++) {
echo '<p>'.$authors_array[$x].'</p>';
}
echo '</td>';
或者你可以逃脱php并且不使用echo:
//php-code
...
?>
<tr>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["year"]; ?></td>
<td>
<?php for($x=0; $x < count($authors_array); $x++) {
echo '<p>'.$authors_array[$x].'</p>';
} ?>
</td>
</tr>