获取除列中数据之外的数据

时间:2014-12-05 17:46:47

标签: php mysql

所以我有以下代码:

require_once('db.php');

$getUsers = mysqli_query($db, 'SELECT * FROM users');
$rows = [];

while ($r = mysqli_fetch_assoc($getUsers)) {
    $rows[] = $r;
    $getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
    while($r = mysqli_fetch_assoc($getSkills)) {
        $rows['skills'] = $r;
    }
}


print(json_encode($rows));

哪个输出:

[{"id":"1","name":"user1","skills":{"woodcutting":"6","mining":"10"}},{"id":"2","name":user2"}]

有两个问题:

  • 我想在表skills中获取所有数据除了id,或者至少在用json编码之前将其删除。
  • 出于某种原因,我无法获得第一个用户之后显示的“技能”。 user2还应该有一个技能对象。

我做错了什么?

3 个答案:

答案 0 :(得分:0)

看起来你需要类似的东西:

while($r = mysqli_fetch_assoc($getSkills)) {
    unset($r['id']);
    $rows['skills'] = $r;
}

答案 1 :(得分:0)

  • 第1点:取消设置id unset($r['id'])以从array() $r中删除。在未设置id之前,将id保留为变量,因为您将其用于下一个查询。
  • Point-2:可能skills这些ID中没有数据存在。结果你没有得到skills。建议您通过这些ID查询skills表中是否存在任何数据。

    while ($r = mysqli_fetch_assoc($getUsers)) {
        $id = $r['id'];
        unset($r['id']);
        $rows[] = $r;
        $getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '$id'");
        while($r = mysqli_fetch_assoc($getSkills)) {
            $rows['skills'] = $r;
        }
     }
    

答案 2 :(得分:0)

要获取表id中除skills之外的所有列,您可以列出要选择的所有列,如下所示:

mysqli_query($db, "SELECT column1, column2, another_column FROM `skills` WHERE id = '" . $r['id'] . "'");

或者,您可以SELECT所有内容并使用unset()在json-encoding之前清除id列:

$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
while ($r = mysqli_fetch_assoc($getSkills))
{
    unset($r['id']);

    // whatever it is that you want to do.
}

除了最后一个用户(?)之外,不显示skills,因为您在while循环的每次迭代中重新分配它。以下是您可以做的事情:

require_once('db.php');

$getUsers = mysqli_query($db, 'SELECT * FROM users');
$rows = array();

while ($r = mysqli_fetch_assoc($getUsers))
{
    $skills = array();
    $tempRow = $r;
    $getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
    while ($r = mysqli_fetch_assoc($getSkills))
    {
        unset($r['id']);  // since you don't want the `id`.
        $skills[] = $r;
    }
    $tempRow['skills'] = $skills;
    $rows[] = $tempRow;
}


print(json_encode($rows));

希望有助于:)