三表条件查询 - php mysql

时间:2017-04-19 05:07:15

标签: php mysql html-table

我有三张桌子。

用户

________________________________________________
|User_ID | User Name | user contact information|
------------------------------------------------

学校

________________________________________________________________
|School_ID | School name | school address | school contact info|
----------------------------------------------------------------

照片

___________________________________________
| Picture ID | User_ID | School_ID|file path|
-------------------------------------------

Per School_ID,我想显示如下信息。

学校名称,学校地址,用户名,用户联系信息以及所有符合学校ID的图片。

脚本在php中会是什么? 我在这个网站上研究了几天,尝试了很多代码,但到目前为止还没有任何工作。

这是我用过的代码。

<?php
         $sql="SELECT Schoolname, School_contact_info, email, description, address, website, file, userName FROM school, picture, user WHERE Location_ID=Picture_ID  ORDER BY Location_ID desc";
         $result_set=mysql_query($sql);
         while($row=mysql_fetch_array($result_set))
         {
          ?>
                <div href=<?php $row['Location_ID'] ?>>
                <td><?php echo $row['Location_ID'] ?></td>  
                <td><?php echo $row['name2'] ?></td>
                <td><?php echo $row['email'] ?></td>
                <div><td><?php echo $row['description'] ?></td></div>
                </div>

                <div><img src="uploads/<?php echo $row['file'];?>" alt=" " height="75" width="75"></div>

                <br>
                <?php
         }
     ?>

我想显示学校信息,以及所有将school_ID作为外键的图片。

2 个答案:

答案 0 :(得分:0)

查询应该使用

select school_name,school_address,user_name,user_contact_information
from user,school,picture where user.user_id=picture_id 
and school.school_id=picture.picture_id

    <?php
    $con=mysqli_connect("localhost","my_user","my_password","my_db");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

    // Perform queries 
    mysqli_query($con,"select school_name,school_address,user_name,user_contact_information
    from user,school,picture where user.user_id=picture_id 
    and school.school_id=picture.picture_id");

答案 1 :(得分:0)

在您的表结构中,您没有获得您在查询中使用的所有列详细信息 但试试这个: -

SELECT s.Schoolname, s.School_contact_info, s.email, s.description, s.address, s.website,
 p.file, u.userName 
FROM school as s,
 picture as p on s.School_ID=p.School_ID, 
 user as u on p.User_ID=u.User_ID
WHERE s.Location_ID=p.Picture_ID  ORDER BY s.Location_ID desc

我假设像Location_ID,email,website这样的列来自学校表。