数据交叉匹配 mysql 两个 table,值显示在 table 使用 PHP mySql

Data cross matching with mysql two tables, value display in table using PHP mySql

我在 php 和 mysql 上遇到了一些问题,我什至不知道如何正确地提出这个问题,看起来很复杂。不过,如果有人能帮助我,我将非常感激。

我有两个table (allunit.sql)

id - unit_name
12       -   MIS
14       -   MIT
15       - ENG

当有人从浏览器 (unit_id) 单击注册按钮时,将存储在注册 table 中。如果有人注册到该单元,按钮将显示(已注册),否则将显示 "Enroll" enrollment.sql

enroll_id - unit_id
1         - 12
2         - 14

我正在使用这个查询

$unit = SELECT * FROM allunit;

$enroll = SELECT * FROM enrollment;

$row_enroll = mysqli_fetch_assoc($enroll);

while($row = mysqli_fetch_assoc($unit)) {
    if($row['id']==$row_enroll['unit_id']){
        $button = 'Already enrolled';
    }else{
        $button = 'Enroll';
    }
?>

<tr>
     <td><?php echo $row['id']; ?></td>
            <td><?php echo $row['unit_name']; ?></td>

           <td><?php echo $button; ?></td>
</tr>
<?php } ?>

如果我添加一个单元,该单元的按钮更改为 "already Enrolled",但如果我添加多个,仍然只有一个按钮更改。其他保持不变 "enroll".

我知道我的问题真的很乱,希望你能理解。急需帮助。谢谢

我在您的代码中发现了两个问题:

  1. mysqli_fetch_assoc() 在 MySQL 结果上调用,而不是查询。您需要先致电 mysqli_query()。您可以在文档中查看示例:https://www.php.net/manual/en/mysqli-result.fetch-assoc.php
  2. 当你得到一个结果时,比如 $row_enroll,它是行的集合,所以你不能直接将它与列一起使用,即 $row_enroll['unit_id'] 不会给你任何东西。

最后,像这样在两个单独的数据集之间进行比较似乎不会对您有效,至少对于当前代码而言是这样。考虑仅使用 JOINs 到 return 一个数据集。

首先,您必须告诉数据库 运行 您的查询,将查询放在文本字符串中是不够的。这是完成的,在本例中使用 query() 方法。

其次,由于您希望为每个单元处理一次注册,因此至少将注册卸载到数组中以便于重复使用会很有用

// assuming you have a connection and its in $con

$sql    = 'SELECT * FROM allunit';
$units   = $con->query($sql);

$sql    = 'SELECT unit_id FROM enrollment';
$res2   = $con->query($sql);
// make an array of just the enrolment id's as that all you need
// so we can use in_array() later to do the test for are you already enrolled
$enrols = [];
while ($row = $res2->fetch_assoc()){
    $enrols[] = $row['unit_id'];
}

while ($unit = $units->fetch_assoc() ) {
    if ( in_array($unit['id'], $enrols) ) {
        $button = 'Already enrolled';
    }else{
        $button = 'Enroll';
    }

?>
<tr>
    <td><?php echo $unit['id']; ?></td>
    <td><?php echo $unit['unit_name']; ?></td>
    <td><?php echo $button; ?></td>
</tr>
<?php 
} // endwhile
?>