PHP, mySql Select all with the same name - php

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

Related

how to show name for this ID

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.

MYSQL Group By same id?

I have the following 2 tables :
TABLE 1: user
id s_id first_name last_name
----------------------------------
1 2 test test
2 2 hello test
3 2 now hello
4 1 john smith
TABLE 2: section
id section_name
-------------------
1 first
2 my section
3 other section
based on the above two tables , I would like to write a MYSQL query to :
SELECT ALL from user table and GROUP THEM BY s_id ( SAME s_id) , how could I do that?
I would like to get all the s_id = 2 ALL grouped together as an array or object but controlled by s_id? so I would loop through the s_ids and print out the first and last name?
Here is an Example of the output:
$sections = array['my section'](array('first_name'=>'test' , 'last_name'=>'test'),
array('first_name'=>'hello' , 'last_name'=>'test'),
array('first_name'=>' now' , 'last_name'=>'hello'))
thanks
Simply
SELECT * FROM `user` GROUP BY `s_id`
But you have different question in your title and in your content.
So what you want in PHP is something like this:
while($row = your sql fetch)
{
$array[$row['s_id']][] = array('first_name' => $row['first_name'], 'last_name' => $row['last_name']);
}
print_r($array);
If you need all the users with s_id = 2 than:
SELECT * FROM `user` where `s_id` = 2 # this will give 3 users
otherwise if you group with s_id you'll get only one user for each section, and I think you don't want that
To show all, than you have to run query :
SELECT user.*, section.section_name FROM `user`
INNER JOIN section ON section.id = user.s_id
And trick it in PHP:
$query = "
SELECT
user.*,
section.section_name
FROM `user`
INNER JOIN section
ON section.id = user.s_id
";
$result = mysqli_query($conn, $query);
$final_data = array();
while($data = mysqli_fetch_assoc($result))
{
$final_data[$data['section_name']][] = $data;
}
print($final_data); // to see the result
Take a look at mysqli_fetch_array function in php.
You need to cycle the query result with this php function and put them in an array, you do not need to group anything in sql, but only:
select * from user order by s_id
In the php cycle you can populate your array as you need.

Statement to Count(*) related rows on other table

I have two tables named patient_list and dentist_list where in the dentist can have many patients, I want to get how many patients the dentist has and ordered it.
I have here a sample code where I get each patient of doctor:
$query_dentist = "SELECT * FROM dentist_list ORDER BY ID ASC";
$res_dentist = mysql_query($query_dentist);
if ($res_dentist) {
while ($row_dentist = mysql_fetch_array($res_dentist)) {
}
}
After I get all the dentists, I create a new query inside the while where I will get all the patient count.
$dentist_id = $row_dentist['id'];
$query_patient= "SELECT COUNT(*) as patient_num FROM patient_list
WHERE dentist_id ='$dentist_id'";
$res_patient=mysql_query($query_patient);
if($res_patient)
{
while($row_patient=mysql_fetch_array($res_patient))
{
}
}
For example the output of query is:
doctor 1 has 10 patient
doctor 2 has 5 patient
doctor 3 has 100 patient
Rather than using PHP, is it possible to use a MySQL statement instead? I will create one query only because i need it to sort by number of patient.
You can try using this code:
select d.Name, -- <- put dentist information here
(select count(1) from patient_list p where p.dentist_id = d.dentist_id)
from dentist_list d
order by 2 asc -- <- order by by the 2nd field that is (select count(1...
SELECT COUNT(*) AS Patient_Num FROM patient_list GROUP BY dentist_id ORDER BY 1

Echo results of a complicated INNER JOIN query with multiple tables

This is my first question here. I have a complicated SQL database and I need to join different tables which have the same column names.
"event" is a sports match. It contains tournament_stageFK which is linked to tournament_stage table, which contains tournamentFK which is linked to tournament table, which contains tournament_templateFK which is linked to tournament_template table, which contains sportFK which is linked to sport table.
So in order to find out what sport the match is from, I need to do an inner join, otherwise I'd have to open the database millions of times. The only way to do it is this, but I don't know how to display the results. My poor attempt to echo the results is below:
$SQL = "SELECT sport.name,
country.name,
tournament_template.name,
tournament.name,
tournament_stage.name,
event.*
FROM tournament_template
INNER JOIN sport
ON tournament_template.sportFK = sport.id
INNER JOIN tournament ON tournament.tournament_templateFK = tournament_template.id
INNER JOIN tournament_stage ON tournament_stage.tournamentFK = tournament.id
INNER JOIN event ON event.tournament_stageFK = tournament_stage.id
INNER JOIN country ON tournament_stage.countryFK = country.id
WHERE DATE(event.startdate) = CURRENT_DATE()
ORDER BY sport.name ASC,
country.name ASC,
tournament_stage.name ASC,
event.startdate ASC";
$result = mysql_query($SQL);
while($get=mysql_fetch_array($result))
{
echo $result['event.name'];
echo "<br>";
}
Your result is fetched as an array indexed by column name, which is "name" for several of your columns... the table name sport, country, template, etc is not part of the returned index. So you need to provide column names that will be unique
Set an alias for each of your columns (e.g. SELECT sport.name AS sport_name) then reference it by its alias within your echo (e.g. $result['sport_name']).
You need to use column aliases and access those in your fetch call. Instead of event.*, be explicit about the columns you need:
$SQL = "SELECT sport.name AS sportname,
country.name AS countryname,
tournament_template.name AS templatename,
tournament.name AS tournamentname,
tournament_stage.name AS stagename,
/* Use explicit column names instead of event.* */
event.name AS eventname,
event.someothercol AS someother
FROM tournament_template
...etc...
...etc...";
// Later...
while($row=mysql_fetch_array($result))
{
echo $row['eventname'];
echo "<br>";
}

Returning Mysql result with COUNT( * )

I'm trying to return a count from mysql. My code is below
$number_of_options_sql = tep_db_query("SELECT COUNT( * ) FROM
(select sum(options_id) as total from products_attributes
where products_id='".$products_id."' group by options_id) as total");
$number_of_options_result = tep_db_fetch_array($number_of_options_sql);
When I run this query in Phpmyadmin, it shows the result with COUNT(*) at the table heading. I'm getting the correct result, the query works for me, I just can't print it out on the screen.
I've tried returning the value the following ways and neither print anything on the screen:
echo $number_of_options_result[COUNT( * )];
echo $number_of_options_result[total];
Use AS field_name after COUNT(*)
$number_of_options_sql = tep_db_query("SELECT COUNT(*) AS field_name FROM (select sum(options_id) as total from products_attributes where products_id='".$products_id."' group by options_id) as total");
To print:
echo $number_of_options_result['field_name'];
(Replace "field_name" with any relevant name of your choice)
Your query is assigning an alias to the table/query not the column. use this one below:
$number_of_options_sql = tep_db_query("SELECT COUNT(*) as total FROM (select sum(options_id) as total from products_attributes where products_id='".$products_id."' group by options_id) a");
$number_of_options_result = tep_db_fetch_array($number_of_options_sql);
Also looks like you want to know count of distinct options id for a product_id, I would rewrite the query as follows:
$number_of_options_sql = tep_db_query("SELECT COUNT(DISTINCT options_id) as total FROM products_attributes WHERE products_id='".$products_id."'");
Just edit your query to
SELECT COUNT(*) as count FROM ....
then it will be stored like 'count' and you can print it the $number_of_options_result[count]; way.
put in a variable "total"
$number_of_options_sql = tep_db_query("SELECT COUNT(*) as total
then it works
echo $number_of_options_result['total'];

Categories