How to get multiple row counts merged from mysql_fetch_rows - php

I'm trying to get the total number of product sales in each category, although the database structure being used doesn't really seem to lend itself to this.
I've gotten it to the point where I have the IDs of products (it's own table) in a category (another table) that have only been purchased (still another table). So looping through the category, I choose the IDs in the orders table and try to count the rows. I end up with the item count per item, but any way I try to merge and count them up them doesn't work.
$SQL = "SELECT * from PRODUCTS WHERE CATEGORY LIKE '%-$thiscat-%' AND STATUS = 'Active' AND STOREITEM = 'Yes' AND ID IN ($item_ids)";
$result = mysql_query( $SQL );
while( $row = mysql_fetch_array( $result ) ) {
$sql_active_accounts = "SELECT count(ID) FROM ORDERS WHERE ITEM_NUMBER ='$row[ID]'";
$res_active_accounts = mysql_query($sql_active_accounts);
while($row_active_accounts = mysql_fetch_row($res_active_accounts)){
print_r($row_active_accounts);
}
};
An example that print_r gives for a specific category that only had 3 items sell, but some items sold more than once:
Array ( [0] => 2 ) Array ( [0] => 3 ) Array ( [0] => 1 )
This is correct in that three items sold, sold those number of times.
And array_sum doesn't work on this. I can't seem to do anything to get those numbers to add up. I'm trying to count just specific rows and really don't care about the data in them for the final result.
I understand SQL calls within loops are a bad idea, but this is an admin area script that won't be run often.

$SQL = "SELECT * from PRODUCTS WHERE CATEGORY LIKE '%-$thiscat-%' AND STATUS = 'Active' AND STOREITEM = 'Yes' AND ID IN ($item_ids)";
$result = mysql_query( $SQL ); while( $row = mysql_fetch_array( $result ) ) {
$sql_active_accounts = "SELECT count(ID) FROM ORDERS WHERE ITEM_NUMBER ='$row[ID]'";
$res_active_accounts = mysql_query($sql_active_accounts);
$int_total = 0;
while($row_active_accounts = mysql_fetch_row($res_active_accounts) {
foreach($row_active_accounts as $i)
$int_total += $i;
}
// Use $int_total for total value
Some like this should do the trick for your if I understand you correctly.

Try this
$query = mysql_query("select distinct(pgroup) from test") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo $row['pgroup']."=>";
$query1="SELECT count(*),pname FROM `test` where pgroup='$row[pgroup]' group by pname ";
$result1=mysql_query($query1) or die(mysql_error());
$rows1=mysql_num_rows($result1);
while($row_sub=mysql_fetch_array($result1)) {
$query2 = "select * from test where pname = '".$row_sub['pname']."'";
$res2=mysql_query($query2) or die(mysql_error().'errror here');
$row2 = mysql_num_rows($res2);
echo $row_sub['pname']."=".$row2."<br/>";
}
}

Related

Displaying Row Count for Data in PHP

Been at this awhile...this is actually another simplified question to a problem I posted earlier. I'm trying to display the country and count for the following query:
$query = mysqli_query($con, "SELECT COUNT(id), country FROM users GROUP BY country ORDER BY COUNT(id) DESC");
while ($row = mysqli_fetch_array($query)) {
$countries = $row['country'];
echo $countries;}
What I'm getting in output is the countries listed from highest to lowest, but it does not have the count displayed next to it. I know these have been summed in the query, how do I target the number & assign it to a php variable for display?
Any help would be appreciated.
You can use an alias for your COUNT column and then reference that in the array returned by mysqli_fetch_array for each row.
$query = mysqli_query($con, "SELECT COUNT(id) AS countryCount, country FROM users GROUP BY countryCount ORDER BY countryCount DESC");
while ($row = mysqli_fetch_array($query)) {
$count = $row['countryCount'];
$countries = $row['country'];
echo $count;
echo $countries;}
You need to add alias in query for COUNT(id) like below:-
$query = mysqli_query($con, "SELECT COUNT(id) as count, country FROM users GROUP BY country ORDER BY count DESC");
Now change while() loop code a bit:-
while ($row = mysqli_fetch_assoc($query)) { // _assoc for lighter array iteration
$countries = $row['country'];
$countries_count = $row['count'];// get count of each country
echo $countries.'--'.$countries_count ;// show country and it's count both
}
Is this what you are trying to do:-
$query = mysqli_query($con, "SELECT COUNT(id) AS total_country, country FROM users GROUP BY country ORDER BY id DESC");
while ( $row = mysqli_fetch_array( $query ) )
{
$countries = $row['country'];
$total_countries = $row['total_country'];
echo "<p>{$countries}</p>;
echo "<p>Total count: {$total_countries}</p>";
}
You're not assigning the variable.
Do this: $count = $row['COUNT']; and echo it. It should work

get required result in sql

i have a sql database having two columns
1. id and 2. parent_id
i want to select all ids where parent_id=1 [let the results saved in X array] then,
select all the ids where parent_id in X[] [let the results saved in Y array] then... do the same upto 7 levels at last i want to sum all levels and get that sum in a variable name "number"
what i tried:
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id = ".$parent[id];
$result = mysqli_query($con, $sql);
$lv1 = mysqli_fetch_array($result);
then again
$sql = "SELECT count(id) as leadersearch FROM `$database`.`$mem` where parent_id in ($lv1)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
and so on.... it may give me required result but it is too much code...
i want to the same by using a loop or something else... to shorten the code.
Your first query gets count(id) and then second query uses it to get results. It seems you have many flaws in your requirement to begin with.
However, for your question you can use sub-query like following
$sql = "SELECT count(id) as leadersearch
FROM `$database`.`$mem`
WHERE parent_id in (
SELECT id FROM `$database`.`$mem` where parent_id = ".$parent['id']."
)";
$result = mysqli_query($con, $sql);
$lv2 = mysqli_fetch_array($result);
If you have many level nesting and you want to search records like this then you can consider functions:
function getLeader($parent_id){
$results = [];
$sql = "SELECT id as leadersearch FROM `$database`.`$mem` where parent_id in (".$parent_id.")";
$result = mysqli_query($con, $sql);
foreach($row = mysqli_fetch_array($result)){
$results[] = $row['id'];
}
return $results;
}
$leaders = [];
$ids = getLeader($parent['id']);
foreach($ids as $id){
$leaders[$id] = getLeader($id);
}

Ranking list with all the users

I have a database (GAMES) with userid, name, sports and points.
user1, football, 10 points -
user1, Basketball, 5 points
user2, footbal, 8 points -
user2, Baketball, 3 points
To get the rank of each user by each sports, I am using the following code which is working perfect:
$sql = "SELECT
sports,
FIND_IN_SET(footbal, (
SELECT GROUP_CONCAT(sports
ORDER BY points DESC)
FROM ".GAMES."
)
) AS rank
FROM ".GAMES."
WHERE userid = 1
";
Results:
user1 (1) (1 is the rank)
When I use user2 in WHERE I get: user2 (2)
Now I want a list like this (For more than 1000 users):
1- User1 (1)
2- User2 (2)
3- User15 (44)
3- ....
Any help will be appreciated. I you need more explanation, just ask.
I would do something like this:
$sqls = array();
foreach ($sports as $sport) {
$sqls[] = "SELECT name FROM ".GAME." WHERE sports='".$sport."' ORDER BY points ASC"
}
Then loop through slqs variable to get all the lists.
And finally, to get the parenthesis part, I would do when I will print the list.
You could have 1 select like this:
$sql = 'SELECT * from table_GAMES WHERE points >= 1000 ORDER BY name'
The result would have all users with more than or equal to 1000 sorted alphabetically. You can then display it like this:
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo $row['name'];
echo ' (' . $row['points'] . ')';
}
MySQL does not really implement ranking in a convenient way. This is discussed, for example, here: ROW_NUMBER() in MySQL
In that thread linked above you can see some solutions you could try, or alternatively you could use some simpler SQL to get an ordered list and use PHP to calculate/count the ranks:
// ...
$sql = 'SELECT userid, sports, SUM(points) AS total_points FROM games GROUP BY userid, sports ORDER BY sports, SUM(points) DESC';
$result = $mysqli->query($sql);
$rank = null;
$last_sport = null;
$sports_ranking = array();
while($row = $result->fetch_object()) {
if($row->sports == $last_sport) {
$rank++;
} else {
$rank = 1;
}
$sports_ranking[$row->sports][] = array(
'userid' => $row->userid,
'rank' => $rank,
'total_points' => $row->total_points
);
}
echo('<pre>'); print_r($sports_ranking); echo('</pre>');
// ...
Wouldn't this work?
"SELECT * FROM GAMES WHERE userid = ".$userid." ORDER BY points DESC"
I don't see why you would need to use anything else, as you are just ordering by their points.
or if you also want to specify a sport,
"SELECT * FROM GAMES WHERE userid = ".$userid." AND sports = '".$sport"' ORDER BY points DESC"
You would need to use an array to loop through each sport then just use the above query again.
e.g.
$ranks = mysql_query("SELECT * FROM GAMES WHERE userid = ".$userid." AND sports = '".$sport"' ORDER BY points DESC", $database);
$count = 1;
while(list($userid, $name, $sport, $points) = mysql_fetch_row($ranks)) {
//formatting here. table row, paragraph etc or:
echo "$count - $name ($userid)";
$count++;
}

Fetching the result array from mysql query in php, while loop issue

I have this table in MySql db:
After running this query:
SELECT score, count(*) FROM Coaches group by score ORDER BY score DESC
The result table look like this:
Now in php I try to fetch the result and iterate through the array to determine which group each coach belongs to and get his place in the ranking. Therefore I wrote this:
$groupsOfScoresQuery = "SELECT score, count(*) FROM Coaches group by score ORDER BY score DESC";
$result = mysqli_query($dbc, $groupsOfScoresQuery);
if ($result) { // query did successfully run
$response['topCoaches'] = array();
if (mysqli_num_rows($result) > 0) {
while ( $rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
$currentRanking++;
$score = array(); // temp user array for one group of scores
$numberOfCoaches; // Number of coaches with this particular number of scores
$scoresGroup; // Scores in the particular group
$score["scores"] = $rowScore["score"];
$score["count"] = $rowScore["count(*)"];
$numberOfCoaches = $score["count"];
$scoresGroup = $score["scores"];
$response["scoresGroup"] = $scoresGroup; // HERE IS THE PROBLEM
.
.
.
more processing
} // end WHILE
Why $response["scoresGroup"] will always conatins the last value from the result? In this case this is 123. I thought that this is the first iteration through the loop and $response["scoresGroup"] wll hold first element (474), during the second iteration should hold 382 ? What I'm doing wrong here? Do I use correct function to fetch result? or should I use different loop to acheive my goal? Thanks for the help in advance.
You did not post the expected structure of $response; here is what I think you are trying to do:
while ($rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$response["scoresGroup"][] = array(
"scores" => $rowScore["score"],
"count" => $rowScore["count(*)"]
);
}
// $response["scoresGroup"][0]["scores"] = 474
// $response["scoresGroup"][0]["count"] = 1
// $response["scoresGroup"][1]["scores"] = 382
// $response["scoresGroup"][1]["count"] = 1
// $response["scoresGroup"][2]["scores"] = 123
// $response["scoresGroup"][2]["count"] = 1
Or perhaps:
while ($rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$response["scoresGroup"][$rowScore["score"]] = $rowScore["count(*)"]
}
// $response["scoresGroup"][474] = 1
// $response["scoresGroup"][382] = 1
// $response["scoresGroup"][123] = 1
if (mysqli_num_rows($result) > 0) {
while ( $rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
$currentRanking++;
$score = array(); // temp user array for one group of scores
$numberOfCoaches; // Number of coaches with this particular number of scores
$scoresGroup; // Scores in the particular group
$score[]["scores"] = $rowScore["score"];
$score[]["count"] = $rowScore["count(*)"];
$numberOfCoaches[] = $score["count"];
$scoresGroup[] = $score["scores"];
$response[]["scoresGroup"] = $scoresGroup; // HERE IS THE PROBLEM
Looking at the description of your question, you need to define a multidimensional array for storing all the results from query resultset.
Please refer the below code snippet
$groupsOfScoresQuery = "SELECT score, count(*) FROM Coaches group by score ORDER BY score DESC";
$result = mysqli_query($dbc, $groupsOfScoresQuery);
if ($result) { // query did successfully run
$response['topCoaches'] = array();
if (mysqli_num_rows($result) > 0) {
while ( $rowScore = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
$currentRanking++;
$score = array(); // temp user array for one group of scores
$numberOfCoaches; // Number of coaches with this particular number of scores
$scoresGroup; // Scores in the particular group
$score["scores"] = $rowScore["score"];
$score["count"] = $rowScore["count(*)"];
$numberOfCoaches = $score["count"];
$scoresGroup = $score["scores"];
$response["scoresGroup"][] = $scoresGroup; //Notice the array here
.
.
.
more processing
} // end WHILE
You are settings $response['scoresGroup'] each time you run the loop, so at the end, it will contain only the last element. Try changing the variable you put the data into on each loop.
$x++;
$response['scoresGroup' . x] = $scoresGroup;

mysql SELECT a whole column or cycle through all IDs

I need to select a whole column.
So my question is how do i get a whole column ?
$query = "SELECT * ";
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
I tried id=* but no luck ...
My goal is to cycle through all IDs but some may be missing so i figured i put them in a numeric or associative array and use foreach. If there is a better way , please do share.
EDIT:
function get_all_ids()
{
global $connection;
$query = "SELECT * ";
$query .= "FROM employees ";
$query_result = mysql_query ( $query , $connection );
confirm_query($query_result);
$query_result_array = mysql_fetch_assoc($query_result);
return $query_result_array;
}
i use this to print the array
$all_id = get_all_ids();
// preparing the table;
echo "<pre>";
print_r($table);
print_r($all_id);
echo "</pre>";
and this is the array
Array
(
[id] => 1
[department_id] => 1
[name] => jordan
[EGN] => 9108121544
[email] => testEmail
[address] => testAddress
[country] => testCounty
)
If there's more than one row in your result set, you need to keep fetching until all results are retrieved:
$q = mysql_query('SELECT * FROM `table`');
while (($row = mysql_fetch_assoc($q)) != FALSE)
{
// Do something with *one* result
}
mysql_free_result($q);
If you'd like to retrieve all ids in a single fetch, you could do:
$q = mysql_query('SELECT GROUP_CONCAT(`id`) AS `id_list` FROM `table`');
$row = mysql_fetch_assoc($q);
mysql_free_result($q);
$list_of_ids = explode(',', $row['id_list']);
WARNING: GROUP_CONCAT() usually has a result limit of 1024 bytes; meaning your results will be truncated for large tables. You could either resort to the first solution, or increase group_concat_max_len for the current connection.
If you want ALL the records then you dont need a WHERE condition at all.
Perhaps you mean the simple:
SELECT id
FROM employees
ORDER BY id ASC
If this gives you only one row, then either you have only one row or you are adding a LIMIT 1 or your PHP code does not loop through all the results but just shows the first one of them. Please add the PHP code.
If you want to select a single column. Then do not use "*", give the name of the columns name separated by comma and quoted with "`" (tick) for safety.
$query = "SELECT `id` "; //if you only want to get ids from the table
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";

Categories