php while loop to select categories - php

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.

Related

while-Loop in foreach-Loop with mysqli_query leads to unexpected result

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>';
}
?>

Take data from URL in MySql DB

I would like to take data from DB via simple script
<a href='category.php?CAT=Shoes'>Shoes</a>
then simple show all rows with the specific data in "CAT" column like this:
$CAT = $_GET['CAT'];
$sql = "SELECT * FROM Shop WHERE CAT = $CAT" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo"
... results
"}}
The problem is that this script does work with INT (for example SELECT CAT = 5 like category.php?CAT=5) but not with VARCHAR (SELECT CAT = Shoes like category.php?CAT=Shoes). Now I'm not sure why is this happening.
With Error: Trying to get property of non-object
$sql = "SELECT * FROM Shop WHERE CAT = '$CAT'"
You need pass $cat as string
$cat = $_GET['CAT'];
$sql = "SELECT * FROM Shop WHERE CAT = '{$cat}'" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<pre>' . print_r($row, true) . '</pre><br/>';
}
}

nested loop but avoiding the repetition of first loop

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>';
}
?>

select fields and group them in a category in php and mysql

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;
}
}

Creating an array of IDs from a while loop

Im trying to generate an array but not sure how to go about it.
I'm currently getting my data like so:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test#test.com'");
$row = mysql_fetch_array($query);
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT * FROM usersettings WHERE userId = ".$row['userId']." AND usersettingCategory".$row1['categoryId']." LIKE 'y'");
$isyes = mysql_num_rows($query2);
if($isyes > 0){
$cat1 = mysql_query("SELECT * FROM shops WHERE shopstateId = 1 AND (categoryId1 = ".$row1['categoryId']." OR categoryId2 = ".$row1['categoryId']." OR categoryId3 = ".$row1['categoryId'].")");
$cat1match = mysql_num_rows($cat1);
if($cat1match > 0){
while($cat1shop = mysql_fetch_array($cat1)){
$cat1msg = mysql_query("SELECT * FROM messages WHERE shopId = ".$cat1shop['shopId']." and messagestateId = 1");
while($cat1msgrow = mysql_fetch_array($cat1msg)){
echo $cat1msgrow['messageContent']." - ".$cat1msgrow['messageCode'];
$cat1img = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$cat1shop['shopimageId']);
$imgpath = mysql_fetch_array($cat1img);
echo " - ".$imgpath['shopimagePath']."<br/>";
}
}
}
}
}
But this can cause duplicates when a user has all 3 of a shops categories picked in their preferences. I am trying to find a way to just pull the message ID out instead of the whole thing and put it into an array giving me, for example:
1,3,5,7,1,3,5,2,4,7,8
Then I can just run a separate query to say get me all messages where the ID is in the array, but i am unsure of the most constructive way to build such an array and examples of array from a while loop I have seen do not seem to be what I am looking for.
Is there anyone out there that can push me in the right direction?
Can't help with this code. But if you want an array from a query without duplicate result, you can use " select DISTINCT (id) " in your query or for more simple solution :
$id_arr = array();
$sql = mysql_query("select id from id_table");
while ($id_result = mysql_fetch_array($sql) {
$id = $id_result['id'];
if (!in_array($id, $id_arr)) {
$id_arr[] = $id;
}
}
I have found a much easier way to create the required result. I think at 6am after a hard night coding my brain was fried and I was making things a lot more complicated than I needed to. A simple solution to my issue is as follows:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test2#test2.com'");
$row = mysql_fetch_array($query);
$categories = "(";
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT usersettingCategory".$row1['categoryId']." FROM usersettings WHERE userId = ".$row['userId']);
$row2 = mysql_fetch_array($query2);
if($row2['usersettingCategory'.$row1['categoryId']] == y){
$categories .= $row1['categoryId'].",";
}
}
$categories = substr_replace($categories ,")",-1);
echo $categories."<br />";
$query3 = mysql_query("SELECT * FROM shops,messages WHERE shops.shopId = messages.shopId AND messages.messagestateId = 1 AND (shops.categoryId1 IN $categories OR shops.categoryId2 IN $categories OR shops.categoryId3 IN $categories)");
while($row3 = mysql_fetch_array($query3)){
$query4 = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$row3['shopimageId']);
$row4 = mysql_fetch_array($query4);
echo $row3['messageContent']." - ".$row3['messageCode']." - ".$row4['shopimagePath']."<br />";
}

Categories