Joshua Joshua - 5 months ago 7
PHP Question

How to get the highest value from a sum of values in php that is not in MySQL

Good Day, I have a table in php that sums up the values that is stored in MySQL.

MySQL table:

USER 1:
crit_1 = 75
crit_2 = 75
USER2:
crit_1 = 100
crit_2 = 100


My PHP goes like this:

$crit_1 = $row["crit_1"];
$crit_2 = $row["crit_2"];
$sum = ($crit_1 + $crit_2);
$total = number_format ($sum / 2, 2, '.',' ');


and here is my HTML

<th><strong>Score from Crit_1</strong></th>
<th><strong>Score from Crit_2</strong></th>
<th><strong>TOTAL SCORE OF crit_1 and crit_2</strong></th>

<td align="center"><?php echo $crit_1; ?></td>
<td align="center"><?php echo $crit_2; ?></td>
<td align="center"><?php echo $total; ?></td>


Now this sums up crit_1 and crit_2 that is stored in MySQL using PHP. What I wanted to do is to get the highest value from the third column which is
$total
and place it in another column or another textbox somewhere (any would do)

What I tried so far is.

$value = max($total);
$key = array_search($value, $total);

<td align="center"><?php echo (max($total)); ?></td>


but I am having this error:

max(): When only one parameter is given, it must be an array


So I guess my real question is, How can I convert $total into an array of string, so I can get the highest value. Or if you do have any other approach to my problem. THanks.

Answer

I have created a array named $max_total and each time during looping insert $total value in it. Then use max() fuction to get max.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$mysql_database = "a";

$max_total = array();
$conn = mysqli_connect($servername, $username, $password) or die ("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
$result =  mysqli_query($conn, "select * from reg")or die("error");
echo '<table border="1">';
echo '<tr><th><strong>Score from Crit_1</strong></th>
<th><strong>Score from Crit_2</strong></th>
<th><strong>TOTAL SCORE OF crit_1 and crit_2</strong></th></tr>';
while($row = mysqli_fetch_assoc($result)){
    $max_total[] = $row['crit_1'] + $row['crit_2'];
    echo '<tr><td align="center">'.$row['crit_1'].'</td><td align="center">'.$row['crit_2'].'</td><td align="center">'.($row['crit_1'] + $row['crit_2']).'</td></tr>';
    }
echo '</table>';
echo(max($max_total));

Change table name and database name according to yours.

for more info about please raed http://php.net/manual/en/function.max.php