2016-07-01 5 views
0

おはよう、私はMySQLに格納されている値を合計したテーブルをPHPで作成しています。MySQLにないPHPの値の合計から最大値を得るには

MySQLのテーブル:

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

私のPHPはこのように書きます:

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

とここに私の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> 

は、今は、この中に格納されcrit_1とcrit_2をまとめていますMySQLはPHPを使用しています。私がやりたかったのは、第3列の最高値を$totalとし、それを別の列や別のテキストボックスに置くことです(いずれでも可能です)。

これまでに何を試みましたか?

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

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

が、私はこのエラーを持っています:

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

だから私は私の本当の問題は、私は、文字列の配列に$合計を変換することができますどのように、であるので、私は最高の値を取得することができますね。または、私の問題に対する他のアプローチがある場合。ありがとう。

+0

をラエドてください?そのタグが無関係な場合は削除する必要があります。 –

+0

* My Query is this this *これはクエリではなく、PHPコードです。 – shmosel

+0

私はMySQLテーブルの例を含んでいます。私はちょうど私が正しい道にいるかどうかを知りたかったが、何かをする必要があるか、あるいはmax()よりも何か別のことをする必要がある。 – Joshua

答えて

0

は、私はそれでloopinginsert $総value中にarray命名$max_totalとするたびに作成されました。最大値を取得するにはmax()fuctionを使用してください。あなたによると

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

変更table namedatabase name。詳細は

についてhttp://php.net/manual/en/function.max.php mysqlのはこのためだ、またはこれは、質問の種類を「あなたのためにそれを書く」である

+0

これは働いた。しかし、それはショーンのコメントと同じです。もう一度おねがいします – Joshua

+0

最後の1つの質問は、どのように私は最高の値を持つ行全体をエコーすることができますか?スコアだけでなく、 – Joshua

+0

あなたのテーブルにプライマリIDを持っていれば、あなたの$ max_totalを作成する際にプライマリIDをinside whileループのようなキーとして作成するのがとても簡単です。 $ max_total [$ row ['id']] = $ row ['crit_1'] + $ row ['crit_2'] ;.次に、最大値のIDを取得し、そのIDを使用して希望の結果を取得する – user1234

関連する問題