查询多个表,显示错误

时间:2016-03-23 15:35:58

标签: php mysql

<?php

DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'xxxxxxxxxxxxxxxx');
DEFINE ('DB_NAME', 'bigbobsveterinarysurgery');


$dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect, check the details ' . mysqli_connect_error());
mysqli_set_charset($dbc, 'utf8');
$q = "SELECT dog_name, owner_name, vet_date, Breed, cost, address, contact_number FROM owner, dogs ORDER BY dog_name ASC";      
$r = @mysqli_query ($dbc, $q);


    echo '<table>
    <tr>
    <th scope="col">Dog</th>
    <th scope="col">Owner</th>
    <th scope="col">Entry Date</th>
    <th scope="col">Breed</th>
    <th scope="col">Cost</th>
    <th scope="col">Address</th>
    <th scope="col">Contact Number</th>
    </tr>'
    ;


    while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
        echo '<tr><td>' . $row['Dog_name'] . '</td><td>' . $row['owner_name'] . '</td><td>' . $row['vet_Date'] . 
        '</td></tr>' . $row['Breed'] . '</td></tr> ' . $row['cost'] . '</td></tr> '. $row['address'] . '</td></tr> ' . $row['contact_number'] . '</td></tr> ';
    }

echo '</table>';
?>

显示所有数据的品种,成本和联系号码。我想要的表的格式在下面找到,但每只狗都列在每个其他所有者,所有其他列都是空白。发布日期没有显示,但我认为这是一个问题,从我从Excel工作表导入数据和日期格式错误

修改

我已将其更新为:

while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
        echo '<tr><td>' . $row['Dog_name'] . '</td><td>' . $row['owner_name'] . '</td><td>' . $row['vet_Date'] . 
    '</td><td>' . $row['Breed'] . '</td><td> ' . $row['cost'] . '</td><td> '. $row['address'] . '</td><td> ' . $row['contact_number'] . '</td></tr> ';
}

这已经停止了beginnign的整个混乱,所有数据现在都在表中格式化。但是,每只狗仍然与每个单独的主人匹配。这个帖子或数据库中的代码是一个问题吗?

1 个答案:

答案 0 :(得分:0)

我认为你需要加入两个表

$q = "SELECT dog_name, owner_name, vet_date, Breed, cost, address, contact_number 
      FROM owner o
      LEFT JOIN dogs d ON o.id = d.owner_id 
      ORDER BY d.dog_name ASC";      
// make sure you join on valid columns.
// also, if there is a column that appears in both tables, 
// to avoid ambiguity, prefix it with the corresponding table alias
$r = @mysqli_query ($dbc, $q);

echo "<table>
    <tr>
    // skipping this so it doesn't eat up too much space
    </tr>";

// also, every `$row[something]` should be placed inside a `<td></td>`, like so:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
    echo '<tr>
            <td>' . $row['Dog_name'] . '</td>
            <td>' . $row['owner_name'] . '</td>
            <td>' . $row['vet_Date'] . '</td>
            <td>' . $row['Breed'] . '</td>
            <td>' . $row['cost'] . '</td>
            <td>' . $row['address'] . '</td>
            <td>' . $row['contact_number'] . '</td>
        </tr> ';
}

从两个表中选择会在它们之间产生笛卡尔积 使用join,您只能获得相应的行(根据ON子句)。

在您的特定情况下,使用join将保持狗主人关系,而使用FROM owner, dogs,您将获得每位所有者的所有狗,这可能不是您所追求的。< / p>