Displaying Row Count for Data in PHP - 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

Related

How to sum of MySQL table column in php?

I want to get the sum total of the table columns in my database.
I've tried using the following code but have not been successful.
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(value) AS value_sum FROM User_Table');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
echo $sum;
Thank you very much!!
I hope you try to find total number of record of a table of User_Table
$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
$result = mysqli_query($link,'SELECT SUM(your_column_name) AS value_sum FROM User_Table');
//or like the query for return last row that indicate total number of record
// id auto increment
$result = mysqli_query($link,'SELECT * FROM User_Table ORDER BY id DESC LIMIT 1;');
$row = mysqli_fetch_assoc($result);
$sum = $row['id'];
echo $sum;
// or using count
$result = mysqli_query($link,'SELECT COUNT(*) total_row FROM User_Table;');
$row = mysqli_fetch_assoc($result);
$sum = $row['total_row '];
echo $sum;
As of my understanding you need count the number of columns your database have. If I am not wrong, you may please use the query below
select * from information_schema.columns
where table_schema = '<YOUR DATABASE NAME>'
order by table_name,ordinal_position
Hope this helps. Thanks

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

Getting exact value from fetched array from MySql

Not a duplicate of Select specific value from a fetched array
I have a MySql database as:
Here's my query:
$sql = "SELECT * FROM data ORDER BY Score DESC";
I want it to be a leaderboard which people can update their scores so I can't use
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
I want to get Username of the second row in my query.So I wrote:
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
}
echo "Result = '".$row[1]['Username']."''";
}
?>
But it returns Result = '' like there's nothing in the array.
But if I write
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Name = '".$row['Username']."''";
}
}
It will return : Parham, Mojtaba, Gomnam, Masoud,
So what am I doing wrong in the first snippet?
You can not access $row outside of while loop.
So store result in one new array, and then you can access that new array outside the while loop:
$newResult = array();
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$newResult[] = $row;
}
}
echo "Result = '".$newResult[1]['Username']."''"; // thus you can access second name from array
Because you write where condition after ORDER by at
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
The sequence of query is
SELECT * FROM data // select first
WHERE ID = 1
ORDER BY Score DESC// Order by at last
Check http://dev.mysql.com/doc/refman/5.7/en/select.html
And for second case you need to fetch Username inside while loop and use $row['Username'] instead $row[1]['Username']
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Result = '".$row['Username']."''";// write inside while loop
}
You can assign row value to any array and use that array.
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
$rows = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$rows[] = $row;
}
echo "Result = '".$rows[1]['Username']."'";
}
?>
Or if you want only second highest score from column you can user limit as
$sql = "SELECT * FROM data ORDER BY Score limit 1,1";

Echo the 2 last columns of tabel

I have a table and i want to echo the 2 last rows of my tabel, I used the below code but just the last one showed, what is the problem.
$result1 =(mysql_fetch_array(mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")));
Print $result1['time'];
mysql_fetch_array = 1 fetch.
do it again for fetching 2nd result.
Also, use mysqli eh.
You're doing mysql_fetch_array only one time, so it gets the first element. If you want to get all the elements, then do it again, or use a loop.
Something like:
$query = "SELECT * FROM $table ORDER BY id DESC LIMIT 2";
while($row = mysql_fetch_array(mysql_query($query) )
{
echo $row['time'].'<br>';
}
For 2 Or more rows you need to loop it
$sql = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")
while($row=mysql_fetch_array($sql))
{
echo $row['time']."<br>";
}
$query = mysqli_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2");
while ($result = mysqli_fetch_array($query)) {
echo $result['time'];
}
Gives out every return of your database (2 in this case). You should use mysqli_-functions.
Maybe you should try like this, since mysql_fetch_array returns only one row
while ($row = mysql_fetch_array($yourQuery)) {
echo $row["yourAlias"];
}
Further details here : http://fr2.php.net/manual/en/function.mysql-fetch-array.php
My solution:
$limit = 2;
$sql = "SELECT * FROM $table ORDER BY id DESC LIMIT $limit";
$result = mysql_query($sql);
$array = array(); $i = 0;
while($row = mysqli_fetch_array($result))
{
$array[$i] = $row;
$i++;
}
var_dump($array[0]);
var_dump($array[1]);

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