HOW TO CALCULATE PERCENTAGE WITH MYSQL

Asked

Viewed 90 times

-2

 ID  tiposang 
 1     A+
 2     A-
 3     B+
 4     O-

Good evening ,I’m doing a project and in my database I have a table similar to this one above, i would like to know how I do to perform a query that shows the percentage that each blood type present in my BD and that each percentage of this is saved in a certain variable to be used in a php code

1 answer

0

To begin, you would need to create a PHP query that shows you the amount of table records.

I created a very simple example of how you can do, using 3 queries for you to better understand.

I suppose your table is called tb_tipo_sanguinho

$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'sangue';

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);


$result = $mysqli->query('SELECT COUNT(*) AS total FROM tb_tipo_sanguino')->fetch_array();

$A_positivo = $mysqli->query('SELECT COUNT(*) AS APOSITIVO FROM tb_user WHERE tiposang = "A+"')->fetch_array();
$A_negativo = $mysqli->query('SELECT COUNT(*) AS ANEGATIVO FROM tb_user WHERE tiposang = "A-"')->fetch_array();

$total      = $result['total'];
$A_positivo = $A_positivo['APOSITIVO'];
$A_negativo = $A_negativo['ANEGATIVO'];

echo '<pre>';
print_r('A+: '.$A_positivo); print_r(' ('.porcentagem_nx($A_positivo, $total).'%)');
echo '<pre>';
print_r('A-: '.$A_negativo); print_r(' ('.porcentagem_nx($A_negativo, $total).'%)');
echo '<pre>';
print_r('TOTAL: '.$total);

function porcentagem_nx ( $parcial, $total ) {
    return ( $parcial * 100 ) / $total;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.