显示来自php

时间:2017-12-16 16:22:45

标签: php mysql database

我有两张桌子,一张是书,另一张是书。它们通过一对多关系相关联,即编写器中的主键,即w_id是由b_writer命名的书中的外键。但是当我在php脚本中打印b_writer时,它会打印id,即一个数字,但我想要写作者的名字。我该怎么办?

$connect = mysqli_connect("localhost", "root", "", "ecom");  
$query = "SELECT * FROM books WHERE b_id = '".$_POST["book_id"]."'";  
$result = mysqli_query($connect, $query);
    while($row = mysqli_fetch_array($result))  
{  
    echo $row["b_id"] $row["b_desc"] $row["b_name"] $row["b_writer"];
}

打印b_writer时,如何打印作者姓名。

2 个答案:

答案 0 :(得分:2)

您应该使用连接来获取表格中的数据,例如:

"SELECT b.*, w.* 
 FROM books as b
 INNER JOIN writer as w on b.b_writer = w.w_id
 WHERE b_id = '".$_POST["book_id"]."'"; 

但请注意在查询中使用var,否则会面临sqlinjection风险

为了避免这种情况 您应该使用prepare语句和绑定参数,例如:

$stmt = $db->prepare("SELECT b.*, w.* 
  FROM books as b
  INNER JOIN writer as w on b.b_writer = w.w_id
  WHERE b_id =?");
$stmt->bind_param("i",$_POST["book_id"] );
$stmt->execute();

答案 1 :(得分:0)

使用join

更改您的查询

select a.*,b.* from book as a inner join writer b on a.b_id = b.id where b_id = '".$_POST["book_id"]."'