Remove Duplicate Values From Select Option In PHP - php

here's the code and i want to echo only 1 city from mysql database!
<?php
include('db.php');
$queryss = mysqli_query($conn, 'SELECT * FROM areas');
while ($rowx = mysqli_fetch_array($queryss)) {
echo "{pro:'$rowx[1]',city:'$rowx[2]', dist:'$rowx[3]', town:'$rowx[4]', area:'$rowx[5]',subarea:'$rowx[6]',ucname:'$rowx[7]'},";
}
?>
and i'm, getting this input here! 3 time karachi in my html, but i want only 1 of this city. SELECT DISTINCT is working in mysql but how can i use it in PHP?

Your query should be
SELECT * FROM areas GROUP BY id
I have tested it.

Use
SELECT DISTINCT column_name1,column_name2 FRAM areas
in your SQL where column_nameN stands for the columns you need for your output.
OR use something like this (untested):
$results = [];
while ($rowx = mysqli_fetch_array($queryss)) {
$results[] = $rowx;
}
$results= array_unique($results);
foreach($results as $rowx) {
echo "{pro:'$rowx[1]',city:'$rowx[2]', dist:'$rowx[3]', town:'$rowx[4]', area:'$rowx[5]',subarea:'$rowx[6]',ucname:'$rowx[7]'},";
}

First Solution
You can insert distinct keyword into your SQL to accomplish what you need, like so
SELECT DISTINCT your_column_name FROM table_name
Second Soltion
You can execute your SQL statement and then use array_unique, to be like so
$selectStatement = mysqli_query($con, 'SELECT * FROM areas');
$selectedArrayValues = mysqli_fetch_array($selectStatement);
$selectedUniqueArrayValues = array_unique(selectedArrayValues);
// Then return that array to your HTML code
I recommend the first solution because it's more optimized

Related

How to remove duplicates from json in PHP

I have a MySQL, PHP code as follows.
$sql = "SELECT * FROM shipschedule WHERE ship_date BETWEEN '2016-08-01' AND '2016-8-31'";
$result = $mysqli->query($sql);
$e = array();
while($r = $result->fetch_array()) {
$rows = array();
$rows['title'] = $r['title'];
$rows['start'] = $r['ship_date'];
array_push($e, $rows);
}
echo json_encode($e);
The above php code echos
[{"title":"111","start":"2016-08-10"},
{"title":"111","start":"2016-08-10"},
{"title":"111","start":"2016-08-10"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]
My question is how I can echo the above as follow instead. Please see that duplicate start dates will be removed by title.
[{"title":"111","start":"2016-08-10"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]
title 111 has the same 3 start dates, and I need to display it like
{"title":"111","start":"2016-08-10"},
title 222 has the same 2 start dates, and I need to display it like
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]
You could prevent receiving duplicates, and reduce requesting unnecessary data by adjusting your query.
SELECT DISTINCT title, start FROM ...
It would be much easier (and probably faster too) to just get the right (unique) data from MySQL. This can be achieved with the distinct modifier:
SELECT DISTINCT title, start
FROM shipschedule
WHERE ship_date BETWEEN '2016-08-01' AND '2016-8-31'

How i can compare the result in one query or two?

I am trying to fetch last 10 topics from smf database but topics are in two separate tables.
Subject, Post Time and Message ID in smf_messages.
Topic ID and Topic First Message in smf_topics.
I wrote this code to fetch topics but i dont know how to compare these two results.
$result = mysql_query("select subject,id_msg,id_topic from smf_messages");
$result2= mysql_query("select id_first_msg from smf_topics");
if(mysql_num_rows($result)!=0)
{
while($read = mysql_fetch_object($result))
{
if ($read->id_msg==$read->id_topic) {
echo "<a href='../index.php?topic=" . $read->id_topic . "'>".$read->subject."</a><br>";
}
}
You probably want the following query
select subject, id_msg, id_topic, id_first_msg
from smf_messages
left join smf_topics on smf_message.id_msg = smf_topics.id_first_msg
bind the records by joining in sql:
select subject id_msg, id_topic, id_first_msg from smf_messages
join smf_topics on smf_messages.id_msg = smf_topics.id_topic
mysql have many many options, with a small google search you could found about left join.
tuttorial and examples.
Fist thing you have to do is stop using mysql_* and start using mysqli_* or pdo learn about sql injections
Your query should look like this.
select smf_messages.subject,smf_messages.id_msg,smf_messages.id_topic from smf_messages left join smf_topics on smf_topics.id_first_msg=smf_messages.id_msg
If you want to do that without using SQL, this is my solution it's not good but you can have an idea of how it works:
$messages = array();
$topics = array();
while($readmessage = mysql_fetch_object($resultmessage)) {
array_push($messages, $readmessage);
}
while($readtopic = mysql_fetch_object($resulttopic)) {
array_push($topics, $readtopic);
}
foreach ($topics as $topic) {
$result = array_search($topic->id_first_message);
if($result != true){
//HERE $result IS THE INDEX OF FIRST MESSAGE IF IT IS IN THE MESSAGES ARRAY
$messages[$result].id_msg //Access message attributes
}
}

Counting the number of times each variable appears in table

Basically, I am seeking to know if there is a better way to accomplish this specific task.
Basically, what happens is I query the db for a list of "project needs" -- These are each uniquer and only appear once.
Then, I search another table to find out how many members have the required "skills - which are directly correlated to the project needs".
I accomplished exactly what I was trying to do by running a second query and then inserting them into an array like this:
function countEachSkill(){
$return = array();
$query = "SELECT DISTINCT SKILL_ID, SKILL_NAME FROM PROJECT_NEEDS";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result)){
$query = "SELECT COUNT(*) as COUNT FROM MEMBER_SKILLS WHERE SKILL_ID = '".$row['NEED_ID']."'";
$cResult = mysql_query($query);
$cRow = mysql_fetch_assoc($cResult);
$return[$row['SKILL_ID']]['Count'] = $cRow['COUNT'];
$return[$row['SKILL_ID']]['Name'] = $row['SKILL_NAME'];
}
arsort($return);
return $return;
}
But I feel like there has to be a better way (perhaps using some kind of join?) that would return this in a result set to avoid using the array.
Thanks in advance.
PS. I know mysql_ is depreciated. It is not my choice on which to use.
SELECT P.SKILL_ID, P.SKILL_NAME, COUNT(M.SKILL_ID) as COUNT FROM PROJECT_NEEDS P INNER JOIN MEMBER_SKILLS M
ON P.SKILL_ID=M.SKILL_ID
GROUP BY P.SKILL_ID, P.SKILL_NAME
I've adjusted Nriddens answer to accomodate for the select distinct, Im under the belief that his adjustment would be ok given SKILL_ID is a primary key
function countEachSkill(){
$return = array();
$query = "
SELECT
COUNT(*) AS COUNT,
PROJECT_NEEDS.SKILL_NAME,
PROJECT_NEEDS.SKILL_ID
FROM
(SELECT DISTINCT
SKILL_ID, SKILL_NAME
FROM
PROJECT_NEEDS) AS PROJECT_NEEDS
INNER JOIN
MEMBER_SKILLS
ON
MEMBER_SKILLS.SKILL_ID = PROJECT_NEEDS.SKILL_ID
GROUP BY PROJECT_NEEDS.SKILL_ID";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result)){
$return[$row['SKILL_ID']]['Count'] = $row['COUNT'];
$return[$row['SKILL_ID']]['Name'] = $row['SKILL_NAME'];
}
arsort($return);
return $return;
I am subquerying on the select distinct because I dont believe you have a dedicated skills table with an auto inc primary key, if that was there I wouldn't be using a subquery.
Can you test this query
select project_needs.*,count(members_skills.*) as count from project_needs
inner join members_skills
on members_skills.skill_id=project_needs.skill_id Group by project_needs.skill_name, project_needs.skill_id

PHP: MYSQL to TEXTBOX

I have a problem today. Where I was displaying the value of "fldFrom" in my php form from database. And I can successfully display it. But my problem is, how can I display only once even there is a same word in "fldFrom". Like, in my fldFrom there are same value of "06/24/2013" so then when I test it, the result is "06/24/2013 06/24/2013" because in my database of "fldFrom" has a two value but different row.. I want them to be combine as one.
Here's my code:
<?php
$all = mysql_query("SELECT fldFrom FROM tbldata WHERE fldWeek = '$get_week'");
while ($row = mysql_fetch_array($all))
{
echo "<input type='text' name='play[]' value='" . $row['fldFrom']."'>";
}
?>
Here's my database:
*I want to display the result of fldFrom in just once only...Not twice like this one
thanks
you can use distinct in SELECT statment like this:
$all = mysql_query("SELECT DISTINCT fldFrom FROM tbldata WHERE fldWeek = '$get_week'");
for more information check it here http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html
Edit1:
you can do same with group by, like this:
$all = mysql_query("SELECT fldFrom FROM tbldata WHERE fldWeek = '$get_week' GROUP BY fldFrom");
Just use the DISTINCT operator of SQL:
SELECT DISTINCT fldFrom FROM tbldata WHERE fldWeek = '$get_week'
DISTINCT removes duplicates for you.

PHP & MySql - array foreach [duplicate]

This question already has answers here:
Subquery returning more than 1 row
(3 answers)
Closed 1 year ago.
I want to run a foreach loop from database, but I dont know how to start. I have an array which I have generated from a while loop:
/* mysql query for geting leave_type ID */
$leaveType = mysql_query("
SELECT `leave`.leave_type_id_leave_type,
`leave`.staff_leave_application_staff_id_staff,
`leave`.date,
`leave`.date_updated,
`leave`.active
FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
GROUP BY `leave`.leave_type_id_leave_type
");
/* Now put all leave Type ID in an array */
echo "<table>";
$types = array();
while($leaveFW = mysql_fetch_array( $leaveType )){
$types[] = $leaveFW['leave_type_id_leave_type'];
}
print_r($types);
Now I want to run a foreach loop which will query below code for each ID in array. :
$leaveQ = mysql_query("SELECT Count(*) as total, monthname(date) as
month FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
and `leave`.leave_type_id_leave_type = $type");
I want to show $leaveQ['month'] and $leaveQ['total'] in foreach loop.
May be my foreach like this, but how to get $type['month'] and $type['total'] :
foreach ($types as $type)
{
$leaveQ = mysql_query("SELECT Count(*) as total, monthname(date) as month
FROM `leave` WHERE `leave`.staff_leave_application_staff_id_staff = $iid
and `leave`.leave_type_id_leave_type = $type");
}
May youwant something like this
foreach($types as $result)
{
$iid = $result['staff_leave_application_staff_id_staff'];
$type = $result['leave_type_id_leave_type'];
$leaveQ = mysql_query("SELECT Count(*) as total, monthname(date) as
month FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
and `leave`.leave_type_id_leave_type = '".$leaveFW['leave_type_id_leave_type']."'");
while($row = mysql_fetch_assoc($leaveQ))
{
echo $row['month']."<br>";
echo $row['total']."<br>";
}
}
Don't do this!
mysql_ functions are deprecated as of PHP 5.5!
doing this (get one query, then run another query for each rows in a foreach loop) is a bad approach, commonly seen in a lot of code flying around the 'net...
Also, I think you want to get the count for each month; in that case you have to use the GROUP BY clause for that
The proper way to do this is using JOIN operations, and instead of a query for each line, only one query to get all the data.
Blindly following that advice, not changing too much, just merging the two queries, your query should look like this:
SELECT Count(*) as total, monthname(date) as month, types.leave_type_id_leave_type
FROM `leave`
JOIN (SELECT DISTINCT `leave`.leave_type_id_leave_type
FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid) as types
ON leave.leave_type_id_leave_type = types.leave_type_id_leave_type
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
GROUP BY monthname(date), types.leave_type_id_leave_type
Differences to your approach:
the inner query is almost the same as your 1st query, but
instead of GROUP BY, I used the DISTINCT - in this case, it is the same, but I think this is easier to read - and that is an important aspect!
I only selected the relevant column for it (leave_type_id_leave_type)
I altered the outer query a bit more
the JOIN does what replaces the "foreach" approach
only those rows are "taken into count" (in this case, literally :) ), that are appropriate for the inner query
this will return the count for each month and each type.
To make this even better:
Use properly parametrized prepared statements: better performance, and getting used to it makes you avoid SQL injection in situations where that applies...
you can use PDO for that, it is not deprecated...
Looking at the resulting query, it is easy to see that this can be further simplified, and does not need the inner query, also getting rid of one filter on $iid
SELECT Count(*) as total, monthname(date) as month, leave_type_id_leave_type
FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
GROUP BY monthname(date), leave_type_id_leave_type
Differences now:
huge performance jump...
a lot less, and a lot readable code
EDIT
Here is the SQL fiddle to see how this works
foreach($types as $type){
$leaveQ = mysql_query("SELECT Count(*) as total, monthname(date) as
month FROM `leave`
WHERE `leave`.staff_leave_application_staff_id_staff = $iid
and `leave`.leave_type_id_leave_type = $type");
while($leave = mysql_fetch_assoc($leaveQ)){
var_dump($leave['total'] , $leave['month']);
}
}
If I understand correctly you want to loop thru the types found from your block of code and then issue more database queries and extract more data.
You can basically reuse your first block of code again, wrapped with a foreach loop:
foreach($types as $type){
$query = mysql_query("YOUR_SQL_USING_$TYPE");
while($row = mysql_fetch_array( $query )){
print_r($row);
// or print($row['COLUMN_NAME']);...
}
}

Categories