SELECT duplicate columns in MYSQL database PHP - php

I have a database table titled products.
I have 2 columns in the table titled name and image
I have 4 entries in my database
item 1 | image1.jpg
item 2 | image1.jpg
item 3 | image1.jpg
item 4 | image2.jpg
I need to display the results on a page but I only need to display image.1jpg once, my while() loop is obviously displaying all 4 images.
I've been at this for hours, please help!
My code:
$query = mysql_query("SELECT * FROM products WHERE page='Birthdays' ORDER BY id ASC");
while($fetch = mysql_fetch_assoc($query)){
$image = $fetch['image'];
$name = $fetch['name'];
echo ''.$name.'';
echo '<img src="'.$thumbnail_image.'"/>';
}

What you need is using GROUP BY in your query. So change the query as
SELECT * FROM products WHERE page='Birthdays' GROUP BY image ORDER BY id ASC

Try the code below;
$query = mysql_query("SELECT * FROM products WHERE page='Birthdays' GROUP BY image ORDER BY id ASC");
while($fetch = mysql_fetch_assoc($query)){
$image = $fetch['image'];
$name = $fetch['name'];
echo ''.$name.'';
echo '<img src="'.$thumbnail_image.'"/>';
}

You can also use a trick like not using while statement at all. If you just write the
$fetch = mysql_fetch_assoc($query) without while you would just get the first result in the query. I hope this helps.

Related

Most Efficient way to MySQL Query inside query

i'm just learning PHP, and i have a question
Let just say, i have MySQL table "A"
Name | Job
--------|---------
Jynx | 1
Micah | 4
Nancy | 3
Turah | 1
And another table "B"
JobId | JobName
-------|-----------
1 | Lawyer
2 | Architec
3 | Farmer
4 | Mage
5 | Warrior
So supposedly in php i want to draw table that showed the content of table "A", but instead of displaying number at the "Job" colomn, they each display Job names from Table "B".
What is the most efficient way to do that?
For now, i just thinking of using
$conn = My database connect setting
$sql = "SELECT * FROM tableA ORDER BY Name";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>". $row['Name'] ."</td><td>";
$sql2 = "SELECT * FROM tableB WHERE JobId=$row['Job']";
$result2 = $conn->query($sql2);
while($row2 = mysqli_fetch_assoc($result2)) {
echo "<td>". $row2['JobName'] ."</td></tr>;
}
}
But wouldn't it take a lot of calculating proccess if there is multiple similliar colomn with hundreed of rows?
Is there any more efficient way to do this?
Sorry for my bad english
Thank you for your attention.
A join is definitely the way to go here.
SELECT a.Name, b.JobName
FROM tableA a
JOIN tableB b on (a.Job = b.JobId)
ORDER BY a.Name
Well, it is not easy to learn about JOIN, no time for now, but i will get to learn it latter.
As for now, i just get the idea to just use ARRAY instead
So before i draw the main table, i assign the supportive table (Table B) into associative array
$sql = "SELECT * FROM tableB ORDER BY Id";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
$job[$row['JobId']] = $row['JobName'];
}
And at the main table
$sql = "SELECT * FROM tableA ORDER BY Name";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>". $row['Name'] ."</td><td>". $job[$row['Job']];
}

How can I show all data under specific category using sql query?

well, I have 2 Mysql table which structure is bellow :
Table Jobs
job_id---job_cat_id---job_title---job_description---job_data----is_active
=========================================================================
1 1 title 1 description 1 2016-05-06 1
2 2 title 2 description 2 2016-05-06 0
3 2 title 3 description 3 2016-05-06 1
Table job_details
job_cat_id---job_cat_name
=========================
1 cat name 1
2 cat name 2
3 cat name 3
Now I want to show all jobs under each category from jobs table. E.g
What I need to show :
Job Category 1
1. job 1 from category 1
2. Job 2 from category 1
Job Category 2
1. Job 3 from category 2
So to do this I am using following sql query but can't get the correct result :
$get_job = mysqli_query($conn, "SELECT jobs.job_id, jobs.job_title, job_category.job_cat_name FROM jobs LEFT JOIN job_category ON job_category.job_cat_id = jobs.job_cat_id WHERE jobs.is_active = '1' ");
while($result = mysqli_fetch_array($get_job) ) {
$job_id = (int) $result['job_id'];
$job_title = htmlspecialchars($result['job_title']);
$job_category = htmlspecialchars($result['job_cat_name']);
echo "<h4>$job_category</h4>";
echo "<p>$job_title</p>";
}
Now, It's showing me all category with all jobs but I want to show all jobs under each category.
What is showing now :
Job Category 1
1. job 1 from category 1
Job Category 1
1. Job 2 from category 1
Job Category 2
1. Job 3 from category 2
First we have to remember that the result from a SELECT query is a newly generated table. It is not a multi dimensional array. If it were a multidimensional array, then you could get away with printing the job category at the beginning of each new array which could be grouping up all the jobs in a single category, however since this is not the type of result obtained by the SQL SELECT QUERY, you are printing the job category after each line:
echo "<h4>$job_category</h4>";
echo "<p>$job_title</p>";
Solution:
A solution to your problem would be to first use the ORBER BY ASC in your sql query:
$get_job = mysqli_query($conn, "SELECT jobs.job_id, jobs.job_title, job_category.job_cat_name FROM jobs LEFT JOIN job_category ON job_category.job_cat_id = jobs.job_cat_id WHERE jobs.is_active = '1' ORDER BY job_cat_id ASC");
From there, you know that the jobs in each category should at least be grouped up next to each other (from lowest to highest like 1,1,1,1,2,2,3,3,3). What you can now do is have a conditional print the $job_category if AND ONLY IF it hasn't been printed already previously.
Change this line:
echo "<h4>$job_category</h4>";
into this line:
if ($previous_print != $job_category)
{
echo "<h4>$job_category</h4>";
$previous_print = $job_category;
}
Let me know if it works now.
Another solution may be if you just run one query using group by job_cat_id and then inside loop write another query to get desired result with where clause job_cat_id .
You need to do 2 queries here. Here's an exmaple code, might need some tweaks acording to your table column names:
<?php
$query = "SELECT `job_cat_id`, `job_cat_name`, COUNT(`jobs`.`id`) as `jobs`
FROM `job_category`
GROUP BY `job_cat_id`";
$get_cat = mysqli_query($conn, $query);
$cats = [];
while($result = mysqli_fetch_array($get_cat) ) {
$result['jobs'] = [];
$cats[$result['job_cat_id']] = $result;
}
$get_job = mysqli_query($conn, "SELECT jobs.job_id, jobs.job_title, jobs.job_cat_id FROM jobs WHERE jobs.is_active = '1' AND `job_cat_id` IN (" . implode(',', array_keys($cats)) . ")");
while($result = mysqli_fetch_array($get_job) ) {
$cats[$result['job_cat_id']][] = $result;
}
foreach ($cats as $cat) {
$job_category = htmlspecialchars($cat['job_cat_name']);
echo "<h4>$job_category</h4>";
foreach ($cat['jobs'] as $job) {
$job_title = htmlspecialchars($job['job_title']);
echo "<p>$job_title</p>";
}
}

How to write query for same table same index group

combine one SQL queries from same table same index in PHP MySQL but i just try index name news image select table than than fetch this output view.
this output view image get to databese both are image but two two grouping view
how can its sole query throw
[first image get to databese][1] [third image get to databese][3] [five image get to databese][5] five 7 img ...............
[second image get to databese][2] [fourth image get to databese][4] [six image get to databese][6] six 8 img...............
but i try this query but no work
$numrow =0;
$vali=0;
$sql_q = mysqli_query($conn,"SELECT * FROM tbl_news where cat_id='$cat_id' and cat_id !=19 order by nid DESC");
$ny = mysqli_fetch_array($sql_q);
if mysqli_num_rows($sql_q) > 0) {
while($newsRowi = mysqli_fetch_array($sql_q)){
$row[]=$newsRowi;
}
$n=0;$val=0;
foreach($row as $newsRow ){
$news_img = $newsRow['news_image'];
$f_id = $newsRow['nid'];
$news_heading = substr($newsRow['news_heading'],0,50);
$sq = mysqli_query($conn,"SELECT * FROM tbl_news where nid='ny[0]'");
$ya=mysqli_fetch_array($sq);
$val = $ya['news_image'];
$n++;
$n++;
}
?>
please help me

Selecting a value by row number

I have the following MySQL table:
table_1
id | value_1 | value_2 | value_3
1 hehe haha stack
2 over flow me
3 123 abc hello
4 hi random php
5 html js css
How can I select value_2 from 3rd row, which is "abc"?
Something like $rows[3]['value_2']
Here's the code I had tried with:
$sql=mysql_query("SELECT * FROM table_1 ORDER BY `table_1`.`id` ASC");
$rows=mysql_fetch_array($sql);
//And then I tried accessing it by "$rows[3]['value_2']" and $rows['value_2'][3]
I can't use SELECT * FROM table_1 WHERE id='3', because I need to access multiple lines (all of them). I can't use a WHILE loop also, because I need the values in very different places in the code.
mysql_fetch_array only returns a row corresponding to the query. The proper use of mysql_fetch_array is as such:
$sql=mysql_query("SELECT * FROM table_1 ORDER BY `table_1`.`id` ASC");
while ($row = mysql_fetch_array($sql)) {
printf("ID: %s value_2: %s", $row[0], $row[2]);
}
http://www.php.net/manual/en/function.mysql-fetch-array.php
Found the answer. You can now access them how you wanted.
$sql=mysql_query("SELECT * FROM settings ORDER BY `settings`.`id` ASC");
$id=0;
while ($rows = mysql_fetch_array($sql)) {
$settings[$id]['value_1']=$rows['value_1'];
$settings[$id]['value_2']=$rows['value_2'];
$settings[$id]['value_3']=$rows['value_3'];
$id++;
}
echo $settings[5]['value_3'];
echo $settings[5]['value_1'];
echo $settings[4]['value_2'];
echo $settings[0]['value_3'];

php How to sort and brake while loop based on variable

I have a problem ... I can not solve it for two days. I am a beginner in php.
i don't understand why while loop returns me as much selects fields as every select field has options, for example field "choose color" has 3 options, red green and yellow and i get instead one select field 3 of them... see this http://5dstudio.eu/select.jpg
structure of my data base looks like this:
http://5dstudio.eu/data.jpg
my php code:
<?php
$sql = mysql_query("SELECT qty FROM attributes ORDER BY qty ");
while($row = mysql_fetch_array($sql)){
$name_attribute = $row["qty"];
$num = (int)$name_attribute;
echo "<select>";
$sql2 = mysql_query("SELECT name FROM attributes WHERE qty='$name_attribute' ORDER BY qty");
while($row2 = mysql_fetch_array($sql2)){
$value_attribute = $row2["name"];
echo '<option>' ."$value_attribute". '</option>';
}
echo "</select>";
}
?>
Thanks for any tips and help!
Change your first query to this:
SELECT qty FROM attributes GROUP BY qty
or
SELECT DISTINCT qty FROM attributes

Categories