I have two tables; One is category and the other one is sub_category.
First I want to display all the items in category and store the value of each category and then display all the sub_categories related to that category but the category should not repeat (it should be displayed only once for all sub-categories).
.
<?php
$abcd = $mysqli->query("SELECT * FROM categories;");
while($obj = $abcd->fetch_object())
{
$category = $obj->name;
$results = $mysqli->query("SELECT * FROM `sub-category` WHERE category = '$category';");
while($omg=$results->fetch_object())
{
echo $category. ' '.$omg->subcategory.'<br>';
}
echo $omg->subcategory;
}
?>
Create an array of subcats and implode them so you only get commas where you want them. Only print the $category outside the loop.
<?php
$abcd = $mysqli->query("SELECT * FROM categories ");
while ($obj = $abcd->fetch_object()) {
$category = $obj->name;
$results = $mysqli->query("SELECT * FROM `sub-category` WHERE category = '$category' ");
echo $category.': ';
$subcats = array();
while ($omg = $results->fetch_object()) {
$subcats[] = $omg->subcategory;
}
echo implode(',', $subcats).'<br>';
}
?>
Use a simple JOIN.
<?php
$abcd = $mysqli->query('SELECT DISTINCT categories.name,sub-category.subcategory FROM `categories` JOIN `sub-category` ON category.name = categories.category;');
while($obj = $abcd->fetch_object())
{
echo $obj->name.' '.$obj->subcategory.'<br>';
}
?>
Related
I was trying to fetch some data from mysql using PDO. For example, there is one table for brand names like Mercedes, Audi, Bently, Toyota. And there is another table for car names of each brand. The id s from the 'brand' tables are the foreign keys in the 'cars' table. Now I want to fetch all car names inside each brand name. Here is my code :
// Outer loop for Brands
$query = "SELECT * FROM brand";
$result = $db->query($query);
while($row=$result->fetch(PDO::FETCH_OBJ)){
$brand_name = $row->brand_name;
$brand_id = $row->id;
echo $brand_name;
echo "<br>";
// Inner loop for Cars
$query = "SELECT * FROM cars WHERE brand_id = $brand_id";
$result = $db->query($query);
while($row=$result->fetch(PDO::FETCH_OBJ)){
$car_name = $row->car_name;
echo $car_name;
echo "<br>";
} // Ending of inner loop
} // Ending of outer loop
But I got a problem here. The first brand name is fetched and then the inner loop runs and fetched the car names inside that brand. When the inner loop finished fetching all car names it should go to the outer loop again and find the next brand name. But it is not fetching the rest of the brand names and the car names as well. For example, if it finishes fetching all car names inside Toyota it doesn't go for the next brand name which is Audi.
But if I remove the inner while loop it fetched all the brand names without any errors. Please help me out with your best possible solutions. Thanks in advance.
Try use different var name otherwise you overwrite le first vars
eg $sql, $result and $row and in second $sql2, $result2, $row2
$query = "SELECT * FROM brand";
$result = $db->query($query);
while($row=$result->fetch(PDO::FETCH_OBJ)){
$brand_name = $row->brand_name;
$brand_id = $row->id;
echo $brand_name;
echo "<br>";
// Inner loop for Cars
$query2 = "SELECT * FROM cars WHERE brand_id = $brand_id";
$result2 = $db->query($query2);
while($row2=$result2->fetch(PDO::FETCH_OBJ)){
$car_name = $row2->car_name;
echo $car_name;
echo "<br>";
} // Ending of inner loop
} // Ending of outer loop
You need to change variable names of your inner loop.
Right now you are overriding values of your outer loop in your inner loop (result and row).
// Loop for Brands
$query = "SELECT * FROM brand";
$result = $db->query($query);
while($row=$result->fetch(PDO::FETCH_OBJ)){
$brand_name = $row->brand_name;
$brand_id = $row->id;
echo $brand_name;
echo "<br>";
// Loop for Cars
$query = "SELECT * FROM cars WHERE brand_id = $brand_id";
$result = $db->query($query);
while($row=$result->fetch(PDO::FETCH_OBJ)){
$car_name = $row->car_name;
echo $car_name;
echo "<br>";
} // Ending of inner loop
} // Ending of outer loop
Use bindParam that PDO offers in PHP for setting variables https://www.php.net/manual/en/pdostatement.bindparam.php
Just change the variable names $query,$row and $result for the inner query and everything will work fine.
Your result of the first query held in $result is getting overwritten by the result of inner query
// Outer loop for Brands
$query = "SELECT * FROM brand";
$result = $db->query($query);
while($row=$result->fetch(PDO::FETCH_OBJ)){
$brand_name = $row->brand_name;
$brand_id = $row->id;
echo $brand_name;
echo "<br>";
// Inner loop for Cars
$query1 = "SELECT * FROM cars WHERE brand_id = $brand_id";
$result1 = $db->query($query1);
while($row1=$result1->fetch(PDO::FETCH_OBJ)){
$car_name = $row1->car_name;
echo $car_name;
echo "<br>";
} // Ending of inner loop
}
Your variable names override each other and you should rename them
and also consider using closeCursor() to release resources.
Applying above would look like below:
// Loop for Brands
$sql = "SELECT * FROM brand";
$brandQuery = $db->query($sql);
while ($brandRow = $brandQuery->fetch(PDO::FETCH_OBJ))
{
$brand_name = $brandRow->brand_name;
$brand_id = $brandRow->id;
echo $brand_name;
echo "<br>";
// Loop for Cars
$sql = "SELECT * FROM cars WHERE brand_id = $brand_id";
$carQuery = $db->query($sql);
while ($carRow = $carQuery->fetch(PDO::FETCH_OBJ))
{
$car_name = $carRow->car_name;
echo $car_name;
echo "<br>";
} // Ending of inner loop
$carQuery->closeCursor();
} // Ending of outer loop
$brandQuery->closeCursor();
I have a pice of code to get data from a mysql database. I need to build containers for all stations with the same station_group which I do via a foreach loop. Inside the foreach-loop, there is a while loop to fill the station group containers with all the stations that have the parents station_group. The code works fine if I have debbugging echo lines in the code (so some kind of delay), but having them commented out, the code delivers wrong order of containers and stations. I gues its because of the asynchronous function fetch_assoc so I might put in a callback function, but I just don't get it runnig. Therefore I would appriciate any help... =)
BR
<?php
//build unique Station group array
$sql_unique = "SELECT DISTINCT station_group FROM station ORDER BY station_group ASC";
$unique_station_groups = mysqli_query($dbConn, $sql_unique);
//get all station data
$sql = "SELECT * FROM station ORDER BY station_group, station_id ASC";
$result= mysqli_query($dbConn, $sql);
//Loop for station_group
foreach ($unique_station_groups as $station_group_value){
echo '<div class="css-station-group>';
while ($row = mysqli_fetch_assoc($result)) {
//echo "<script>console.log(".json_encode($station_group_value).")</script>";
//echo "<script>console.log(".json_encode($row).")</script>";
$station_id = $row['station_id'];
$station_name = $row['station_name'];
$station_layout = $row['station_layout'];
$station_group = $row['station_group'];
if ($station_group_value['station_group']==$station_group) {
echo '<div class="station-container css_station-layout-'.$station_layout.
'" id='.$station_id.
'>'.$station_name.
'<br></div>';
}
}
echo '</div>';
mysqli_data_seek($result,0); //reset array, so next Loop will find values again
}
?>
You don't need two queries to do this.
Store the previous station_group and check the current_group and previous group to differentiate the stations.
Changed your code a bit
<?php
//build unique Station group array
// $sql_unique = "SELECT DISTINCT station_group FROM station ORDER BY station_group ASC";
// $unique_station_groups = mysqli_query($dbConn, $sql_unique);
//get all station data
$sql = "SELECT * FROM station ORDER BY station_group ASC";
$result= mysqli_query($dbConn, $sql);
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
//Loop for station_group
// foreach ($unique_station_groups as $station_group_value) {
$current_station_group = null;
echo '<div class="css-station-group">';
foreach ($rows as $row) {
//echo "<script>console.log(".json_encode($station_group_value).")</script>";
//echo "<script>console.log(".json_encode($row).")</script>";
$station_id = $row['station_id'];
$station_name = $row['station_name'];
$station_layout = $row['station_layout'];
$station_group = $row['station_group'];
if ($station_group != $current_station_group) {
echo '<div class="station-container css_station-layout-'.$station_layout.
'" id='.$station_id.
'>'.$station_name.
'<br></div>';
$current_station_group = $row['station_group'];
}
}
echo '</div>';
?>
It looks like it might be easier to simply dump the results in an array then loop through the array.
<?php
//build unique Station group array
$sql_unique = "SELECT DISTINCT station_group FROM station ORDER BY station_group ASC";
$unique_station_groups = mysqli_query($dbConn, $sql_unique);
//get all station data
$sql = "SELECT * FROM station ORDER BY station_group, station_id ASC";
$result= mysqli_query($dbConn, $sql);
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
//Loop for station_group
foreach ($unique_station_groups as $station_group_value){
echo '<div class="css-station-group>';
foreach ($rows as $row) {
//echo "<script>console.log(".json_encode($station_group_value).")</script>";
//echo "<script>console.log(".json_encode($row).")</script>";
$station_id = $row['station_id'];
$station_name = $row['station_name'];
$station_layout = $row['station_layout'];
$station_group = $row['station_group'];
if ($station_group_value['station_group']==$station_group) {
echo '<div class="station-container css_station-layout-'.$station_layout.
'" id='.$station_id.
'>'.$station_name.
'<br></div>';
}
}
echo '</div>';
}
?>
i have a table with staff_id and subjects, i want to display all staffs according to their subjects.
my table
result i want
Physics
-001
-004
-006
Chemistry
-002
-009
Biology
-003
-008
Mathematics
-005
My code
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
echo $subject .'</br>';
echo $staff_id.'</br>';
}
but this doesn't give the result i want.
any help?
What you need is ORDER BY.
Change your query to:
SELECT STAFF_ID, SUBJECT FROM my_table ORDER BY SUBJECT, STAFF_ID
So you get the records in the right order to work with them.
Something like this?
$q = mysql_query("SELECT `staff_id`, `subject` FROM `my_table`;");
$data = array();
while($row = mysql_fetch_array($q)){
$data[$row['subject']][] = '-'.$row['staff_id'];
}
print_r($data);
Or to echo out the rows
foreach($data as $heading => $rows){
echo $heading.'<br>';
foreach($rows as $row){
echo $row.'<br>';
}
}
You can write your code like this below:
$q = mysql_query("SELECT * FROM my_table ORDER BY SUBJECT, STAFF_ID");
while($row = mysql_fetch_array($q)){
//Do staff
}
The following code should help. You should split each subject into a separate array within your query. Once your query is complete, you should iterate through the subject array, and then within each staff id.
$subjects = array();
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
if ($subjects[$row['SUBJECT']] == nil) {
$subjects[$row['SUBJECT']] = array();
}
array_push($subjects[$row['SUBJECT']], $row['STAFF_ID']);
}
foreach ($subjects as $key=>$value) {
echo $key . '<br>;
foreach ($vaue as &$staff) {
echo $staff . '<br>';
}
}
$result=mysql_query("SELECT * from table GROUP BY subject");
while($ext=mysql_fetch_object($result)) {
$query=mysql_query(" SELECT * from table WHERE subject='".$ext->subject."'");
echo $ext->subject;
while($res=mysql_fetch_object($query)) {
echo $res->staff_id;
}
}
I have 1 table on the database :( SQL )
-- id
-- city_name
-- image
and I want to view every images inside them city, for example : USA has 3 images and Canada has 2, it will be looks like :
USA
image 01
image 02
image 03
CANADA
image 01
image 02
I tried this code, it will be view all the records mixed
$results1 = mysql_query("SELECT * FROM gallery");
while($r = mysql_fetch_array($results1)) {
echo $r[city_name]."<hr>";
$city = $r[city_name];
$results2 = mysql_query("SELECT * FROM gallery WHERE city_name='$city'");
while($r = mysql_fetch_array($results2)){
echo '<img border="0" src="'.$r['image'].'">';
}
}
Thanks,
Correction in your code:
You are overwriting `result set $r of first query into second while loop
$last='';
$results1 = mysql_query("SELECT * FROM gallery order by city_name ASC");
while($r = mysql_fetch_array($results1)){
if($last!=$r['city_name']) {
echo $r['city_name']."<hr>";
$last = $r['city_name'];
}
$city = $r['city_name'];
$results2 = mysql_query("SELECT * FROM gallery WHERE city_name='$city'");
while($r1 = mysql_fetch_array($results2)){ //change this variable
echo $r1['image'];
}
}
Second solution:
$data = array();
$results1 = mysql_query("SELECT * FROM gallery");
while($r = mysql_fetch_array($results1)){
$data[$r['city_name']][]=$r;
}
foreach($data as $key=>$images){
echo $key.PHP_EOL; //city name
foreach($images as $image){
echo $image['id'].PHP_EOL; // each image id
echo $image['image'].PHP_EOL; // each image for city
}
}
Simplify your code with one query.
<?php
$cityImages = array();
$res = mysql_query("SELECT * FROM gallery");
while ($row = mysql_fetch_array($res)) {
$cityImages[$row['city_name']][] = $row['image'];
};
?>
Then you can use $cityImages array.
Sorry about the lame title, but I really don't know how to explain it!
Basically, I want to query the game categories from a table, then query games from another table which equal the category of the category queried from the categories table.
Got me so far?
This is the code I have so far...
$get_categories_query = mysql_query("
SELECT *
FROM game_categories
ORDER BY category_name ASC");
while ($row = mysql_fetch_array($get_categories_query)) {
$category_name = $row['category_name'];
$get_category_games = mysql_query("
SELECT *
FROM games
WHERE category = '$category_name'
ORDER BY RAND() LIMIT 5");
while ($row = mysql_fetch_array($get_category_games)) {
$category_game_id = $row['id'];
$category_game_title = $row['game_title'];
$category_game_display .= '<li><img
class="category_module_img"
src="http://www.game.assets.buddyweb.me/' .
$category_game_id .
'/_thumb_100x100.png"></li>';
}
$category_display .= '<div class = "category_module">
<h4>'.$category_name.'</h4>
'.$category_game_display.'
<div class="play_more_btn">More</div>
</div>';
}
But what I get from that is every game appearing from the query from the first category in the list.
I think the problem is the $row variable.
Try this:
$get_categories_query = mysql_query("SELECT * FROM game_categories ORDER BY category_name ASC");
while($row = mysql_fetch_array($get_categories_query))
{
$category_name = $row['category_name'];
$get_category_games = mysql_query("SELECT * FROM games WHERE category = '$category_name' ORDER BY RAND() LIMIT 5");
$category_game_display = false; // new!!
while($row_cat = mysql_fetch_array($get_category_games))
{
$category_game_id = $row_cat['id'];
$category_game_title = $row_cat['game_title'];
$category_game_display .= '<li><img class = "category_module_img" src = "http://www.game.assets.buddyweb.me/'.$category_game_id.'/_thumb_100x100.png"></li>';
}
$category_display .= '<div class = "category_module"><h4>'.$category_name.'</h4>'.$category_game_display.'<div class = "play_more_btn">More</div></div>';
}