PHP looping through an array to fetch a value for each key from database (third normal form)
Posted
by
zomboble
on Stack Overflow
See other posts from Stack Overflow
or by zomboble
Published on 2012-11-08T10:17:02Z
Indexed on
2012/11/08
11:01 UTC
Read the original article
Hit count: 183
I am building a system, mostly for consolidating learning but will be used in practice.
I will try and verbally explain the part of the E-R diagram I am focusing on:
Each cadet can have many uniformID's
Each Uniform ID is a new entry in table uniform, so cadets
(table) may look like:
id | name | ... | uniformID
1 | Example | ... | 1,2,3
uniform
table:
id | notes | cadet
1 | Need new blahh | 1
2 | Some stuff needed | 1
3 | Whatever you like | 1
On second thought, looks like I wont need that third column in the db.
I am trying to iterate through each id in uniformID, code:
<?php
$cadet = $_GET['id']; // set from URL
$query = mysql_query("SELECT `uniformID` FROM `cadets`
WHERE id = '$cadet' LIMIT 1")
or die(mysql_error()); // get uniform needed as string
// store it
while ($row = mysql_fetch_array($query)) {
$uniformArray = $row['uniformID'];
}
echo $uniformArray . " ";
$exploded = explode(",", $uniformArray); // convert into an array
// for each key in the array perform a new query
foreach ($exploded as $key => $value) {
$query(count($exploded));
$query[$key] = mysql_query("SELECT * FROM `uniform` WHERE `id` = '$value'");
}
?>
As I say, this is mainly for consolidation purposes but I have come up with a error, sql is saying:
Fatal error: Function name must be a string in C:\wamp\www\intranet\uniform.php on line 82
line 82 is:
$query[$key] = mysql_query("SELECT * FROM `uniform` WHERE `id` = '$value'");
I wasn't sure it would work so I tried it and now i'm stuck!
EDIT:
Thanks to everyone who has contributed to this! This is now the working code:
foreach ($exploded as $key => $value) {
//$query(count($exploded));
$query = mysql_query("SELECT * FROM `uniform` WHERE `id` = '$value'");
while ($row = mysql_fetch_array($query)) {
echo "<tr>
<td>" . $row['id'] . "</td>
<td>" . $row['note'] . "</td>
</tr>";
}
}
Added the while and did the iteration by nesting it in the foreach
© Stack Overflow or respective owner