简体   繁体   English

从一个表中返回与另一个表中的条件匹配的数据

[英]Echoing data from one table that matches conditions from another

I want to display some data from a MYSQL database in a table format on my webpage. 我想以表格格式在网页上显示来自MYSQL数据库的数据。 So everyone dosent get confused between the website table and mysql table, i'll call the website table 'web table' from now on. 因此,每个人都会在网站表和mysql表之间感到困惑,从现在开始,我将网站表称为“网络表”。

Most of the data for this web table is being pulled from a MYSQL table called 'image', however for one of the web table's columns I want to display data from a different MYSQL table (within the same database) called 'users'. 该Web表的大多数数据都是从称为“图像”的MYSQL表中提取的,但是对于Web表的其中一列,我想显示来自另一个MYSQL表(在同一数据库中)称为“用户”的数据。

Both 'image' and 'users' have a 'user_id' field, so I was looking to find the entry in 'users' where 'user_id' matched the 'user_id' in image. 'image'和'users'都有一个'user_id'字段,所以我想在'users'中找到其中'user_id'与image中的'user_id'相匹配的条目。

Here is the code I have so far. 这是我到目前为止的代码。 I know it is depreciated, but his project requires it. 我知道它已贬值,但是他的项目需要它。

For your reference, the user_id field from 'image' is echo'd as $data[1] 供参考,“ image”中的user_id字段作为$data[1]

mysql_connect('XX','XX','XX');
mysql_select_db('XX')

$order = "SELECT * FROM image ORDER BY id";

$result = mysql_query($order) or die ("Bad query: " . mysql_error() );  

while($data = mysql_fetch_row($result)){
  echo("<tr><td>$data[0]</td><td>'SELECT users.full_name FROM users WHERE users.user_id = $data[1]'</td><td>$data[2]</td><td>$data[3]</td></tr>");
}

Cheers in advanced. 欢呼雀跃。 I know this is probably basic, but I'm not great with PHP. 我知道这可能是基本的,但是我对PHP不太满意。

您可以通过一个INNER JOIN查询获得所需的所有数据

$order = "SELECT a.*, b.full_name FROM image a INNER JOIN user b ON a.user_id = b.user_id ORDER BY a.id";

Another way to do that. 另一种方式。

<?php
mysql_connect('XX','XX','XX');
mysql_select_db('XX')

$order = "SELECT * FROM image as i, users as u WHERE  i.user_id =u.user_id ORDER BY i.id";

$result = mysql_query($order) or die ("Bad query: " . mysql_error() );  

while($data = mysql_fetch_array($result)){
    ?>

  <tr><td><?php echo $data[1]?></td><td><?php echo $data[2]?></td><td><?php echo $data[3]?></td><td><?php echo $data[4]?></td></tr>;

<?php
}

?>

Error is here. 错误在这里。

    <?php 
 while($data = mysql_fetch_row($result)){
    ?>
  <tr><td><?php echo $data[0]; ?></td><td><?php $sql_res = mysql_fetch_assoc(mysql_query('SELECT users.full_name FROM users WHERE users.user_id ="'.$data[1].'"')); ?></td><td><?php echo $data[2] ?></td><td><?php echo $sql_res['full_name'] ?></td></tr>

  <?php
}

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM