I would like to create an array (in php) from sql results like this:
We have the sql-table "Posts" which stores the Name and the Message.Example:
Name | Message
John | Hello
Nick | nice day
George | Good bye
John | where
What i want is to output the names of people who have posted a message but dont display the same names more than 1 time.
So the output would be John,Nick,George.
(From these records, we see that John has posted 2 messages, but at the final output, we see only one time his name).
Is this somehow possible?
Thanks in advance.
Try:
$sql = <<<END
SELECT DISTINCT Name FROM Posts
END;
$query = mysql_query($sql) or die($sql . ' - ' . mysql_error());
$names = array();
while ($row = mysql_fetch_array($query)) {
$names[] = $row[0];
}
print_r($names);
SELECT DISTINCT
You could run a SQL query to just select the distinct names, and nothing else:
SELECT DISTINCT Name FROM Posts;
This will give you a result set consisting of distinct Names values, with each unique value only being returned 1 time in the set.
to get the count you will need to aggregate using group by:
SELECT
NAME
, COUNT(*) as Posts
FROM
Posts
GROUP BY
NAME
Here is the SQL if you are not averse to group BY
select count(name) as N, name from posts group by name ;
People having more than 1 post
select count(name) as N, name from posts group by name having N > 1 ;
Related
I have a problem
not displayed the name for id
data base structure for category_list
id name
1 php
2 mysql
... ...
10 html
and data base structure for entries
category_id
8
5
for the results i have this code, this script displays the ID
as a result it shows 2 , but i want the following to be displayed: mysql
but I want to show name for this ID , instead of ID
We need to use a join query to get the category name for given id, e.g.:
select c.name
from category_list c join entries e on c.id = e.category_id
where category_id = ?
Presumably your database query is something like this:
SELECT category_id FROM some_table
Thus, you're only selecting the ID, not the Name. You can include the Name by joining the other table. Something like this:
SELECT
category_id,
name
FROM
some_table
INNER JOIN category_list
ON some_table.category_id = category_list.id
Then your results would also include the Name value, which you could output to the page:
echo $rows['name']
Run a second query pulling name from category_list like so:
$sql = "SELECT name FROM category_list WHERE id = '$rows['category_id']';";
$result = mysqli_query($conn, $sql);
$category_name = mysqli_fetch_assoc($result);
echo $category_name['name'];
It would however be better to use a JOIN as others like David have pointed out.
So I have a table where some of the products repeat with but have a different value on number of clicks.
name ---- clicks
iPhone 4
Samsung 2
iPhone 1
Samsung 5
my select function is :
$select_table2 = 'SELECT * FROM `mytable`'; //WHERE NAME IS THE SAME
$sql2 = $db->query($select_table2);
while ($row = mysqli_fetch_array($sql2)) {
echo $row["name"];
echo $row["clicks"];
}
I need this output:
iPhone 5
Samsung 7
I don't want to merge the same rows because they have one more column that is different. So please do not suggest simply to merge them and update the clicks...
UPDATE:
$pull_request = 'SELECT SUM(e.product_clicks),e.product_id, u.name, u.product_id FROM `oc_aa_affiliatecollclicktracking` AS e GROUP BY e.product_id LEFT JOIN `'.DB_PREFIX.'product_description` AS u ON e.product_id = u.product_id';
I tried it like this but it's not working
use sum() and also GROUP BY name to get desired output.
$select_table2 = 'SELECT name,SUM(clicks) FROM `mytable` GROUP BY name';
$sql2 = $db->query($select_table2);
while ($row = mysqli_fetch_array($sql2)) {
echo $row["name"];
echo $row["clicks"];
}
while will produce,
iPhone 5
Samsung 7
For more info
SUM()
GROUP BY
EDIT
Group by should come after join.
$pull_request = 'SELECT SUM(e.product_clicks) as clicks,e.product_id, u.name, u.product_id FROM `oc_aa_affiliatecollclicktracking` AS e
LEFT JOIN `'.DB_PREFIX.'product_description` AS u ON e.product_id = u.product_id
GROUP BY e.product_id';
You want to perform a SUM command by group
$query = "SELECT `name`,SUM(`clicks`) FROM `mytable` GROUP BY `name`";
Edit: The other answer was more complete than mine. I forgot to select name field. Added.
What you need is an aggregate function for suming the clicks [SUM(clicks)], and a Group By clause for defining the classification criteria [GROUP BY name].
The other answers where wrong in the sense that are assuming that by changing the select field list adding the aggregate 'SUM', the associative references (eg: index strings of the $row array ) remains the same, the correct query would be:
$select_table2 = 'SELECT name, SUM (clicks) AS clicks FROM mytable GROUP BY name';
Note the alias on SUM(clicks) AS clicks, so the fields returned in the array $row keep their indexes (clicks, names... instead of 'SUM(clicks)')
And the rest is basically the same.
Cheers!
Try :
$select_table2 = 'SELECT name, SUM (clicks) FROM mytable GROUP BY name';
I have two tables first and second.
first Table:
ID NAME ADDRESS
1 test testing address
2 test1 testing address
3 test2 testing address
4 test3 testing address
second Table:
T_ID Partner_id date
1 2 12345678
3 4 32164584
If input T_id is given. Then corresponding Partner_id is taken and it is compared with the ID from first table and corresponding row should be selected.
Can you please tell me.
In php I can write this with two queries but I want it to be in a single query.
Queries in php:
$q=mysqli_query($conn, "SELECT Partner_id from second where T_ID=1");
$qa=mysqli_fetch_array($q);
$w=mysqli_query($conn, "SELECT * from first where ID=$qa[0]");
But, how to combine this two statements?
The specified result can be returned using a query with a join operation.
SELECT f.*
FROM first f
JOIN second s
ON s.Partner_id = f.ID
WHERE s.T_ID=1
Note that there is a potential for this to return more rows that the original, if the first query returns more than one row. (That is, we don't assume that T_ID is unique in second, or that every row with a given T_ID value will have identical values for Partner_id.)
There are other query patterns that will return an equivalent result, but the join operation is the normative pattern.
try to use union ,see this this link
where The SQL UNION operator combines the result of two or more SELECT statements.
SELECT * FROM first WHERE ID IN( SELECT Parent_id FROM second WHERE T_ID = 1 )
or
SELECT * FROM first WHERE ID = ( SELECT Parent_id FROM second WHERE T_ID = 1 )
SELECT * FORM first_table AS f
JOIN second_table AS s
ON s.parent_id =f.id
WHERE s.T_ID = $id
Lets say I have 3 columns and 3 rows, the first column is for ID, the second is names, third is votes. like:
+----+------+-------+
| id | name | votes |
+----+------+-------+
| 1 | bob | 7 |
| 2 | jill | 2 |
| 3 | jake | 9 |
+----+------+-------+
How can I have PHP compare the values in the votes field and sort it by whichever had the highest number, and attach a rank of #1,2,3, etc. depending on how many votes it had?
Each value will be displayed on a separate page. For example, if I went to 'bob's page' with the ID of 1, I would need it to display '#2 bob' since he would be ranked 2nd by votes.
You can make a separate column rank and update it by running the following code whenever your vote changes. This method will make you more efficient as in this you wont be sorting the table again and again when user visits his page:
$q = "select * from tableName order by votes DESC";
$a = mysql_query($q);
$count = 1;
while($arr = mysql_fetch_array($a){
$up = "update tableName set(rank) VALUES($count) WHERE name=$arr['name']";
$aq = mysql_query($up);
$count++;
}
Now on individual pages, you can just retrieve the rank value and show
$user = "Bob";
$q = "select rank from tableName where name=$user";
$a = mysql_query($q);
$arr = mysql_fetch_array($a);
echo $arr[0];
Also this(a slight modification in other answer) should work for you :-
SELECT #rownum:=#rownum+1 AS rank, name, vote FROM table, (SELECT #rownum:=0) as P ORDER BY vote DESC
You could read the values returned by your query into an array and then sort said array.
You want a SELECT query doing an ORDER BY votes, and create a special variable to handle the rank of a row:
SELECT #rownum:=#rownum+1 AS rank, name, vote FROM table, (SELECT #rownum:=0) ORDER BY vote DESC
This query should let you fetch an array with the rank, name, and number of votes of each person of your table.
Alternatively, you can just sort by vote, and add the rank value yourself with PHP.
You can use the MySQL 'ORDER BY' and display those ranks using PHP:
For this example:
<?php
//connection
//DB selection
$query = "SELECT * FROM table_votes ORDER BY votes DESC";
$result = mysql_query($query);
for(int $i=1; $row = mysql_fetch_array($result);i++)
{
echo "#".$i.$row['name']."<br/>";
}
?>
How to select all tables who whas fs_ for example, its not a prefix, its a something added from me , but some tables has it, and i want to select all of them, not choasing the one by one, but to select all tables who starts with fs_
in your MySQL database you can create an extra column that will contain such value.
ex:
ID | NAME | DATE | FS_COLUMN
1 jon 2011 1
2 doe 2005 0
3 tom 2001 1
Then with PHP you can fetch these rows.
$q = mysql_query("SELECT * FROM table WHERE FS_COLUMN='1'");
$r = mysql_fetch_array($q);
$q = $dbc -> ("SELECT COUNT (*) fs_");
$q -> execute();
$count = $q -> rowCount();
echo $count;
It is hard to tell what you are asking or what you are trying to achieve!?
From what you have said try that, if not then please elaborate your question in a more clear and concise way.
well ... it's really no good design approach but to answer your question:
you will probably want to get all matching tables by
SELECT table_name
FROM information_schema.tables
WHERE table_schema = '___YOUR_DB_NAME___'
AND table_name LIKE 'fa\_%'
and construct your query based on the result