id in where子句未定义的索引

时间:2014-12-05 01:28:40

标签: php mysql

如果它有一个另一个表的id,我试图将一些数据附加到数组中,但是我得到了这个:

Undefined index: id

这是我的代码:

$sql = mysqli_query($mysqli, 'SELECT * FROM users');
$rows = [];

while ($r = mysqli_fetch_assoc($sql)) {
    $rows[] = $r;
    $sql2 = mysqli_query($mysqli, "SELECT * FROM skills WHERE id = '" . $rows['id'] . "'");
    while($r2 = mysql_fetch_assoc($sql2)) {
        $rows[]['skills'] = $r2;
    }
}


print(json_encode($rows));

这部分是我遇到麻烦的地方:

$sql2 = mysqli_query($mysqli, "SELECT * FROM skills WHERE id = '" . $rows['id'] . "'");
while($r2 = mysql_fetch_assoc($sql2)) {
    $rows[]['skills'] = $r2;
}

我做错了什么?

3 个答案:

答案 0 :(得分:4)

代码$rows[] = $r表示将$r的值添加到$rows的末尾。因此数组变为:

Array
(
    [0] => Array
        (
            [id] => 1
        )

)

如果您想访问id媒体资源,请使用$rows[0]['id']$r['id']

修改

另请注意,在代码段中,您使用mysql_fetch_assoc代替mysqli_fetch_assoc

答案 1 :(得分:0)

您可能希望使用不同的mySQL来实现您想要的目标。

SELECT `user`.*, `skills`.*
FROM `users`
LEFT JOIN `skills` on `users`.`id` = `skills`.`id`;

以下是JOIN的一个很好的例子 http://www.sitepoint.com/understanding-sql-joins-mysql-database/

答案 2 :(得分:0)

$sql = mysqli_query($mysqli, 'SELECT * FROM users');

while ($r = mysqli_fetch_assoc($sql)) {

$sql2 = mysqli_query($mysqli, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
while($r2 = mysql_fetch_assoc($sql2)) {
    $rows[]['skills'] = $r2;
}
}


print(json_encode($rows));