Print same values once in a while loop - php

$query = mysql_query("SELECT * FROM tblname");
while($fetch =mysql_fetch_array($query)) {
$name = $fetch['name'];
echo "$name";
}
In my example, after echoing out $name in a while, the values are:
Carrots
Lemon
Carrots
Lemon
Is there a way to not repeat printing the same value that will look like this:
Carrots
Lemon
Thank you very much.

$query = mysql_query("SELECT DISTINCT name FROM tblname");
while($fetch =mysql_fetch_array($query)) {
echo $fetch['name'];
}

SQL Solution:
SELECT DISTINCT `name` FROM tblname;
or
SELECT `name` FROM tblname GROUP BY `name`;
PHP Solution:
$my_array = array();
$query = mysql_query("SELECT * FROM tblname");
while($fetch =mysql_fetch_array($query)) {
$my_array[] = $fetch['name'];
}
$my_array = array_unique($my_array);
echo implode('<br />', $my_array);

$names = array();
$query = mysql_query("SELECT * FROM tblname");
while($fetch =mysql_fetch_array($query)) {
$name = $fetch['name'];
if (!in_array($name,$names)){
echo "$name";
$names[] = $name;
}
}
Will work.

$sql = mysql_query("SELECT DISTINCT table1.id, table2.id, table2.name
FROM table1, table2 WHERE id=id GROUP BY name");
This Will Work 100% sure.
SET GROUP BY name and DISTINCT. If not it is not working.

Simply append them into an array like:
$items[] = $item;
After that do:
$items = array_unique($items);
After that, simply print the items.

You can fetch them all into an array and then run array_unique()
$query = mysql_query("SELECT * FROM tblname");
$arr = array();
while($fetch =mysql_fetch_array($query)) {
$arr[] = $fetch;
}
$output = array_unique($arr);
foreach ($output as $uniqe_val) {
echo $unique_val;
}

I find the question ambiguous. I think you're asking for what appears in How to make a list of unique items from a column w/ repeats in PHP SQL

Related

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

How can i join or implode the below array code?

In the below code i want to join or implode all arrays of $trackersurl in a single line. i am getting the results in different lines, so i want to join in a single line.
Can anyone help me out?
I am searching results in stackoverflow, but could not follow.
My code is in below:
$sql = "SELECT * FROM announce WHERE torrent = $id ORDER BY seeders DESC";
$query = #mysql_query($sql);
while ($result = #mysql_fetch_array($query)) {
$trackersurl1 = $result['url'];
$trackersurl2 = "&tr=".$trackersurl1;
$trackersurl = array($trackersurl2);
}
Results of [var.trackersurl] in html page is below:
&tr=http:ajgdsjhg/ann
&tr=udp://iuysidfu/ann
&tr=udp:wutefghgw/ann
&tr=http://sdhgsjdhgj/ann
I want to join them in a single line below
&tr=http:ajgdsjhg/ann&tr=udp://iuysidfu/ann&tr=udp:wutefghgw/ann&tr=http://sdhgsjdhgj/ann
You should be careful of sql injection.
Are you looking to create an array['trackers'] with a string of all the trackers for a magnet link?
<?php
$sql = "SELECT * FROM announce WHERE torrent = ".mysql_real_escape_string($id)." ORDER BY seeders DESC";
$query = mysql_query($sql);
$tracker = null;
if(mysql_num_rows($query)>=1){
while ($result = mysql_fetch_array($query)) {
$tracker .= "&tr=".$result['url'];
}
}
$tracker = array('trackers'=>$tracker);
//$tracker['trackers'] = "&tr=a.com&tr=b.com&tr=c.com";
?>
Try this code
$newArray=array();
while ($result = #mysql_fetch_array($query)) {
$trackersurl1 = $result['title'];
$newArray[] = "&tr=".$trackersurl1;
}
$urlString=implode('',$newArray);

set variable to field name of sql query

My goal here is to set a variable to a field name from a mysql query. Some pseudo code below
1. $query = "SELECT firstName, lastName FROM users WHERE userName = 'mhopkins321';"
2. $result = mysql_query($result);
3. $while($row = mysql_fetch_assoc($result)){
4. $column1 = name_of_column($row['firstName']);
5. }
6. echo $column1
//Would return the string
firstName
obviously line 4 being the real pseudo part
Is this what you're after?
$query = "SELECT firstName, lastName FROM users WHERE userName = 'mhopkins321';"
$result = mysql_query($result);
$all_results = array();
$while($row = mysql_fetch_assoc($result)) {
$formatted_row = array();
foreach ( $row as $column => $value ) {
$formatted_row[] = array($column, $value);
}
$all_results[] = $formatted_row;
}
Or just use $column and $value how you like inside the foreach loop.
Or do you want specifically the first column, which can be accessed with reset($row); $first_key = key($row);?
You want to name a variable with the name of the column?
$$row['firstName'] = $row['firstName'];
Another way is like this:
$query = "SELECT firstName, lastName FROM users WHERE userName = 'mhopkins321'";
$result = mysql_query($result);
$row = mysql_fetch_assoc($result);
foreach($r as $key=>$value){
$$key = $value;
}
Now you can echo the values out by their column name.
This sounds redundant, but you could always use array_search:
while($row = mysql_fetch_assoc($result)){
$value = $row['firstName'];
$key = array_search($value, $row);
}
See more on array_search.

PHP MySQL Get column names While iterating through all records

$query = mysql_query("SELECT * FROM mytable");
while ($row = mysql_fetch_assoc($query)) {
//How to echo column names and values here?
}
Is it possible to echo a table's column names and values while iterating through the entire table in a while loop?
You can use foreach loop
$query = mysql_query("SELECT * FROM mytable");
while ($row = mysql_fetch_assoc($query)) {
foreach($row as $key => $value) {
print "$key = $value <br />";
}
}
$query = mysql_query("SELECT * FROM mytable");
while ($row = mysql_fetch_assoc($query)) {
print_r($row);
}
try this.. column_name is the same name u used in the table
echo $row['column_name'];

how can i controll while loop into another while loop

Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);

Categories