内部连接数据库


Connect database internally

我在数据库中有三个表。

单引号

2类

3-作者

在引号表中,我分配了type_id,它是类型表中的主键,author_id是authors表的主键。

现在,当我想以这种格式一次回显一句话时。

"When you get to my age life seems little more than one long march to 
and from the lavatory."
 By: A. C. Benson   Category: age

那么,如何连接这个数据库来获得这种类型的输出呢?

我试过了,但它只输出报价。

 $sql = "SELECT * FROM quotes LIMIT 1";
 $result = $con->query($sql);
 if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
     echo  " '" " . $row["quote"].  "'"<br><br>";
 }

您应该使用JOIN子句将引号的输出与类型和作者连接起来。

例如,如果每个引号都有一个链接到其他表的字段type_id和author_id,则情况可能是这样的。

SELECT * FROM quotes JOIN types ON quotes.type_id = types.id JOIN authors ON quotes.author_id = author.id

在PHP中,这可能看起来如下:

$sql = "SELECT * FROM quotes JOIN types ON quotes.type_id = types.id JOIN authors ON quotes.author_id = authors.id";
 $result = $con->query($sql);
if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
     echo  " '" " . $row["quote"].  "'"<br>".$row["author"]." ".$row["type"] ."<br>";
 }

当你的桌子看起来像这样时:

quotes:
id, quote, author_id, type_id
types:
id, type
authors:
id, author