【问题标题】:Connect database internally内部连接数据库
【发布时间】:2015-12-13 10:37:41
【问题描述】:

我在数据库中有three tables

单引号

两种类型

三位作者

在quotes表中,我已经分配了type_id,它是types表中的主键,还有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>";
 }

【问题讨论】:

  • 您的代码/数据库中的类别和类型是否相同?还有,你能展示一下报价表的结构吗?
  • 是的类别表示类型,我有链接图像puu.sh/lTNGq/320fd6af2e.png

标签: php mysql database jointable


【解决方案1】:

您应该使用 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

【讨论】:

  • 然后您可以使用$row["column_name"] 中每个连接表的所有行名。如果它们具有相同的名称,例如author 有一个“name”列,quote 有一个“name”列,您可以使用 ALIAS。
  • 您也可以尝试使用别名SELECT quotes.quote, authors.author AS author_name, types.type AS type_name FROM quotes JOIN types ON quotes.type_id = types.id JOIN authors ON quotes.author_id = authors.id,然后尝试$row["author_name"]
  • 当我在 phpmy admin 中运行查询时,SQL 中的一切都很好。但在我的 php 文件中,它给出了错误。 :(puu.sh/lTQFe/246132deac.pngpuu.sh/lTQGg/44b66bad6d.pngpuu.sh/lTQIJ/d6b8cc5e19.png
  • 嗯,您可以尝试使用fetch_array 而不是fetch_assoc,但这应该没什么区别。
  • 您可以使用 fetch-field 列出列名,请参阅php.net/manual/en/function.mysql-fetch-field.php 也许这可以显示列是否到达 php 端
猜你喜欢
  • 2016-06-12
  • 2018-02-14
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多