如何使用sql JOIN查询显示来自多个表的所有数据?

时间:2016-05-26 16:45:51

标签: php mysql

我有以下Mysql表:

1)产品
2)product_images
3)product_date_time
4)product_menu
5)chef_profile

我需要将这5个表中的所有数据显示到名为menu-details.php的页面

所有表的foreign key p_idproducts表ID,而某些表包含多个相同p_id的数据。

要完成此操作,我使用以下mysql连接查询:

$query = mysqli_query($conn, "SELECT p.p_id, p.p_title, p.p_description,

p.p_price, p.p_availability, p.delivery_option, p.event_location,

pimg.p_large_image, pimg.p_small_image, pdt.date, pm.p_menu_title, 

pm.p_menu_description, pm.p_menu_price, pm.p_menu_availability, chef.fname, 

chef.lname, chef.chef_details FROM products as p LEFT JOIN product_images as 

pimg ON p.p_id = pimg.p_id LEFT JOIN product_date_time as pdt ON pdt.p_id = 

p.p_id LEFT JOIN product_menu as pm ON pm.p_id = p.p_id LEFT JOIN 

chef_profile AS chef ON chef.u_id = p.u_id WHERE p.p_id =  '$mid' ") or 

die('wrong query');

要显示我使用以下php代码的数据:

$result = mysqli_fetch_array($query);        
$menu_title =  htmlspecialchars($result['p_title']);

我的问题

  1. 我应该使用5个唯一的 sql查询来向该menu_details.php页面显示数据吗?

  2. 现在,此查询显示来自这些表的单个记录,这些记录具有相同p_id的多个数据。我需要显示具有多个数据的p_id相同的所有数据。我怎么能这样做?

  3. 例如:我在product_images表中有以下数据:

    pimg_id   p_large_image  p_id   u_id  
    
    1         name           203    25  
    1         name           204    26  
    1         name           204    25  
    1         name           205    27  
    1         name           205    28  
    
  4. 所以,如果我使用php while循环,它会显示该表中的所有数据,但它应该显示基于p_id的所有数据,例如p_id = 204

    while($result = mysqli_fetch_array($query)) {
        echo $menu_l_image = htmlspecialchars($result['p_large_image']);
        echo '<br/>';
    } 
    

1 个答案:

答案 0 :(得分:0)

如果p.id是整数,则删除单引号$ mid

protected void Page_Load(object sender, EventArgs e)
{
    TextBox1.Text = "php";

    if (DropDownList1.Items.FindByText(TextBox1.Text) != null)    
    {
         DropDownList1.Text = TextBox1.Text;
    }
    else
    {
        TextBox2.Text = TextBox1.Text;
    }

}

of previus对你可以使用的$ mid vars进行适当的消毒

"SELECT 
    p.p_id, 
    p.p_title, 
    p.p_description,
    p.p_price, 
    p.p_availability, 
    p.delivery_option, 
    p.event_location,
    pimg.p_large_image, 
    pimg.p_small_image, 
    pdt.date, 
    pm.p_menu_title, 
    pm.p_menu_description, 
    pm.p_menu_price, 
    pm.p_menu_availability, 
    chef.fname, 
    chef.lname, 
    chef.chef_details 
    FROM products as p 
    LEFT JOIN product_images as pimg ON p.p_id = pimg.p_id 
    LEFT JOIN product_date_time as pdt ON pdt.p_id = p.p_id 
    LEFT JOIN product_menu as pm ON pm.p_id = p.p_id 
    LEFT JOIN chef_profile AS chef ON chef.u_id = p.u_id 
    WHERE p.p_id =  $mid "