1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Calculating percentages from database

Discussion in 'MySQL' started by ourloop, Aug 23, 2013.

  1. #1
    I have a MySQL database with a table that has a field/column labled "user8" (which is the field for users' state).

    I have this PHP call and its working fine if I call all states individually and I only want numbers of rows.

    <?PHP
    mysql_select_db("my_database") or die(mysql_error());
    $result = mysql_query("SELECT *
    FROM `users`
    WHERE `user8` LIKE '%Georgia%'
    ");
    $num_rows = mysql_num_rows($result);
    
    echo $num_rows - Georgia\n;
    ?>
    Code (markup):
    I would like the MySQL call and the PHP to echo out the lists of all states by percentage.

    i.e.
    United States 50%
    Candana 30%
    etc.

    This is what I have so far.


    <?PHP
    mysql_select_db("my_database") or die(mysql_error());
    $result = mysql_query("SELECT user8, COUNT(*) AS Total, SUM(in) AS TotalIn, SUM(in)*100/COUNT(*) AS Percent FROM lm_users GROUP BY user8
    ");
    $num_rows = mysql_num_rows($result);
    
    echo $num_rows \n;
    ?>
    Code (markup):
    It should work, but doesn't.

    Any help would be appreciated.
    Thanks
     
    ourloop, Aug 23, 2013 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,500
    Likes Received:
    4,460
    Best Answers:
    123
    Trophy Points:
    665
    #2
    I'd stick with getting the count and work out the percentage in the script
     
    sarahk, Aug 26, 2013 IP
  3. vineld

    vineld Greenhorn

    Messages:
    53
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    18
    #3
    I also think it would make sense to do the calculations away from the database in this case. However, it should be possible to do directly. I don't really understand the database structure though. "lm_user" is another table? What is the "in" field? The problem in your query is the group by which you can not use along with sum in that manner.
     
    vineld, Aug 29, 2013 IP