|
Страница 1 из 1 [ Сообщений: 18 ] |
Автор |
Сообщение |
fidukoff
Модератор раздолбай-зануда
|
|
вот есть голосовалка на ПХП, использующая "мускул".
все хорошо, но она, зараза, в сумме не хочет считать проценты равными 100. ТО 95, то 96
В чем проблема? Подскажите! Заранее спасибо!
это код пхпшного файла:
Цитата: | <link rel="stylesheet" href="css.css" type="text/css"> <?php
include("skin.php"); include("dbvars.php"); global $HTTP_POST_VARS; global $HTTP_GET_VARS; global $HTTP_COOKIE_VARS;
@$svrConn = mysql_connect($dbServer, $dbUser, $dbPass) or die("Couldn't connect to the database server"); @$dbConn = mysql_select_db($dbDataBase, $svrConn) or die("Couldn't connect to the database"); // Get the most recent poll id from the database $strQuery = "SELECT pk_Id FROM pollQuestions ORDER BY pk_Id DESC LIMIT 1"; $pResult = mysql_query($strQuery); if($pRow = mysql_fetch_row($pResult)) { $recentPollId = $pRow[0]; } else { die("No poll exists at this point in time."); } if(isset($HTTP_GET_VARS["ViewPoll"])) { ShowVotes(); } else if(!isset($HTTP_GET_VARS["pollId"])) { // Check whether or not this user has already voted if(!isset($HTTP_COOKIE_VARS["has_voted_" . $recentPollId])) ShowPoll(); else ShowVotes(); } else { AddVote(); } function ShowVotes() { /* This function will display the voting poll but will display the results of the poll instead of the available answers */ global $recentPollId; ?>
<html> <head> <title>голосование</title> <style> td { font-family: Verdana; font-size: 8pt; color: #000000; } .header { font-family: Verdana; font-size: 8pt; color: #000000; font-weight: bold; padding-left: 10; padding-right: 10; } </style> </head> <body bgcolor="#ECC88D" text="#000000">
<?php $strQuery = "SELECT * FROM pollQuestions pq "; $strQuery .= "INNER JOIN pollAnswers pa ON pq.pk_Id = pa.pollId "; $strQuery .= "WHERE pq.pk_Id = $recentPollId"; $answertally[0] = 0; $answertally[1] = 0; $answertally[2] = 0; $answertally[3] = 0; $answertally[4] = 0; $answertotal = 0; if($pResult = mysql_query($strQuery)) { while($pRow = mysql_fetch_array($pResult)) { switch($pRow["answer"]) { case $pRow["answer1"]: $answertally[0]++; break; case $pRow["answer2"]: $answertally[1]++; break; case $pRow["answer3"]: $answertally[2]++; break; case $pRow["answer4"]: $answertally[3]++; break; case $pRow["answer5"]: $answertally[4]++; break; } } // Get the total number of votes for($i = 0; $i < sizeof($answertally); $i++) $answertotal += $answertally[$i]; @mysql_data_seek($pResult, 0); $pRow = mysql_fetch_array($pResult) or die("Coundn't view poll. You must vote first."); } else { die("An error occured while trying to display this polls results"); } include("skin.php"); ?> <form class=formvote name="frmVote" action="poll.php?pollId=<?php echo $pRow["pk_Id"]; ?>" method="post"> <table width="350" cellspacing="0" cellpadding="0" border="0" align="left"> <tr> <td height="21" bgcolor="<?=$skinHeader?>" colspan="3"> <span class="header"><?php echo $pRow["question"]; ?></span> </td> </tr> <?php for($i = 1; $i <= 10; $i++) { if($pRow["answer$i"] != "") { ?> <tr> <td bgcolor="<?=$skinBG?>" style="padding-left:10" width="50%" colspan="1" height="21"> <?php echo $pRow["answer$i"] . " [" . number_format(($answertally[$i-1] / $answertotal) * 100, 0, ".", '') . "%]" . "<br>"; ?> </td> <td bgcolor="<?=$skinBG?>" style="padding-left:10" width="45%" colspan="1" height="21"> <img src="line.gif" width="<?php echo ($answertally[$i-1] / $answertotal) * 100; ?>" height="5"> </td> <td bgcolor="<?=$skinBG?>" style="padding-left:10" width="5%" colspan="1" height="21">& </td> </tr> <?php } } include("skin.php"); ?> <tr> <td bgcolor="<?=$skinFooter?>" width="100%" colspan="3" height="21"> <span class="header"> <?php echo $answertotal . " " . ($answertotal == 1 ? "" : "") . "учтено"; ?> </span> </td> </tr> </table> <br> </form> <?php } function AddVote() { /* This function will add a vote to the pollAnswers table and then redirect the user to view the results of the poll */ global $pollId; global $answer; global $recentPollId; global $HTTP_SERVER_VARS; global $HTTP_COOKIE_VARS; $visitorIP = $HTTP_SERVER_VARS["REMOTE_HOST"]; // Did the user choose an option? if($answer == "") { ShowPoll(); } // Has the user already voted? if(isset($HTTP_COOKIE_VARS["has_voted_$recentPollId"])) { ShowVotes(); return; } $strQuery = "INSERT INTO pollAnswers VALUES("; $strQuery .= "0, $pollId, '$answer', '$visitorIP')"; if(mysql_query($strQuery)) { setcookie("has_voted_" . $pollId, 1, time() + 3600 * 24 * 30); ShowVotes(); } else { ?><html> <head> <font color="#000000"></font> <title> результаты голосования</title> <style> body { font-family: Verdana; font-size: 8pt; } h1 { font-family: Verdana; font-size: 16pt; color: darkblue; } </style> </head> <body bgcolor="#ECC88D" text="#000000"> <h1>Voting Failed</h1> An internal error occured while trying to add your vote to the database. <br><br> </body> </html> <?php } }
function ShowPoll() { /* This function will display the latest poll which has been added to the database */ ?>
<html> <head> <title>голосование</title> <style> td { font-family: Verdana; font-size: 8pt; } .header { font-family: Verdana; font-size: 8pt; color: #000000; font-weight: bold; padding-left: 10; padding-right: 10; } </style> </head> <body bgcolor="#ECC88D" text="#000000">
<?php $strQuery = "SELECT * FROM pollQuestions "; $strQuery .= "ORDER BY pk_Id DESC LIMIT 1"; $pResult = mysql_query($strQuery); if($pRow = mysql_fetch_array($pResult)) { include("skin.php"); ?> <form name="frmVote" action="poll.php?pollId=<?php echo $pRow["pk_Id"]; ?>" method="post"> <table width="350" cellspacing="0" cellpadding="0" border="0"> <tr> <td height="21" bgcolor="<?=$skinHeader?>"> <span class="header"><?php echo $pRow["question"]; ?></span> </td> </tr> <tr> <td bgcolor="<?=$skinBG?>" style="padding-left:10"> <?php for($i = 1; $i <= 5; $i++) { if($pRow["answer" . $i ] != "") { ?> <input class=sub2 type="radio" name="answer" value="<?php echo $pRow["answer$i"]; ?>"> <?php echo $pRow["answer" . $i]; ?> <br> <?php } } ?> <br> <input class=sub type="submit" value="голосовать"> <br>& </td> </tr> </table> </form> <?php } else { echo "An error occured while trying to display this poll"; } } ?> |
|
|
 |
|
 |
disko
новый человек
|
|
<?php echo $pRow["answer$i"] . " [" . number_format(($answertally[$i-1] / $answertotal) * 100, 0, ".", '') . "%]" . "<br>"; ?>
вот ета часть округляет
number_format(($answertally[$i-1] / $answertotal) * 100, 0, ".", '') - где 0 - число знаков после запятой

|
|
 |
|
 |
disko
новый человек
|
|
number_format(($answertally[$i-1] / $answertotal) * 100, 0, ".", '')
- изменить на number_format(($answertally[$i-1] / $answertotal) * 100, 2, ".", '')

|
|
 |
|
 |
disko
новый человек
|
|
|
 |
|
 |
Acid~Jazz
соучастник
|
|
disko, fidukoff, вы меня не поняли наверное, да?
Округлять по любому надо, а какие-то части (сотые, тысячные) все равно при округлении будут теряться. Поэтому я и предлагал такую фичу: если в голосовании N пунктов, то считать для N-1 проценты как сейчас, округляя, а для последнего пункта просто написать все что осталось до 100%.
Получается, что если, например, в голосовании три пункта, за первый имеем 31,4536% голосов, а за второй 12,6504%, то мы выводим 31%, 13% процентов, а третий 100-31-13 = 56%.
|
|
 |
|
 |
Protoss
соучастник
|
|
во &%@ - пол часа наборал сообщение - а оно сдохло ……………..
Выдало вместо ответа "Специально для тех, кто в танке: никакого вареза, ссылок и даже намеков на то, где взять варезный софт, серийный номер и пр. здесь НЕ БУДЕТ! Темы и сообщения с подобным содержанием будут удаляться без предупреждения."
вопрос к павлу - что за X#$ ?
_________________ I'm SOLDIER
|
|
 |
|
 |
disko
новый человек
|
|
fidukoff, извини плиз, тут завал конкркетный, все времени код посмотреть нет.…
|
|
 |
|
 |
fidukoff
Модератор раздолбай-зануда
|
|
|
 |
|
 |
|
Страница 1 из 1 [ Сообщений: 18 ] |
Уровень доступа: Вы не можете начинать темы. Вы не можете отвечать на сообщения. Вы не можете редактировать свои сообщения. Вы не можете удалять свои сообщения. Вы не можете добавлять вложения.
|
|