I'm trying to append some data into an array if it has an id of another table, however I'm getting this:
Undefined index: id
This is my code:
$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));
This part is where I'm having trouble at:
$sql2 = mysqli_query($mysqli, "SELECT * FROM skills WHERE id = '" . $rows['id'] . "'");
while($r2 = mysql_fetch_assoc($sql2)) {
$rows[]['skills'] = $r2;
}
What am I doing wrong?
The code $rows[] = $r
means add the value of $r
to the end of $rows
. So the array becomes:
Array
(
[0] => Array
(
[id] => 1
)
)
If you want to access the id
property, either use $rows[0]['id']
or $r['id']
.
EDIT:
Also note that in the code snippet you use mysql_fetch_assoc
instead of mysqli_fetch_assoc
.
You may want to use a different mySQL to achieve what you want.
SELECT `user`.*, `skills`.*
FROM `users`
LEFT JOIN `skills` on `users`.`id` = `skills`.`id`;
Here is a good examples of JOIN http://www.sitepoint.com/understanding-sql-joins-mysql-database/
$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));