Jump to content


Marcos Aurélio - GTI

Member Since 02/07/2010
Offline Last Active 17/12/2010, 11:59
-----

Topics I've Started

Somar Valores Com Php

03/07/2010, 09:51

Estou com o seguinte problema:
Tenho um sistema de OS que fiz para organizar as Ordem de Serviço de minha Assistência técnica de Micros. Segue abaixo o código do arquivo (data.php) que faz a conexão com o DB SQL:
<?php
$hostname_data = "localhost";
$database_data = "dbmiradorma";
$username_data = "root";
$password_data = "lelianamarcos2";
$data = mysql_pconnect($hostname_data, $username_data, $password_data) or trigger_error(mysql_error(),E_USER_ERROR); 
?>
Agora vou mostrar o código do arquivo (visualiza_os_debito.php):
<?php require_once('Connections/data.php'); ?><?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "index.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) 
  $MM_referrer .= "?" . $QUERY_STRING;
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<? require "config/config.php"; ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$maxRows_Recordset1 = $qtd_line_list;
$pageNum_Recordset1 = 0;
if (isset($_GET['pageNum_Recordset1'])) {
  $pageNum_Recordset1 = $_GET['pageNum_Recordset1'];
}
$startRow_Recordset1 = $pageNum_Recordset1 * $maxRows_Recordset1;

mysql_select_db($database_data, $data);
$query_Recordset1 = "SELECT * FROM ordemservico WHERE Arquivo = 'd'";
$query_limit_Recordset1 = sprintf("%s LIMIT %d, %d", $query_Recordset1, $startRow_Recordset1, $maxRows_Recordset1);
$Recordset1 = mysql_query($query_limit_Recordset1, $data) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);

if (isset($_GET['totalRows_Recordset1'])) {
  $totalRows_Recordset1 = $_GET['totalRows_Recordset1'];
} else {
  $all_Recordset1 = mysql_query($query_Recordset1);
  $totalRows_Recordset1 = mysql_num_rows($all_Recordset1);
}
$totalPages_Recordset1 = ceil($totalRows_Recordset1/$maxRows_Recordset1)-1;

$currentPage = $_SERVER["PHP_SELF"];

$queryString_Recordset1 = "";
if (!empty($_SERVER['QUERY_STRING'])) {
  $params = explode("&", $_SERVER['QUERY_STRING']);
  $newParams = array();
  foreach ($params as $param) {
    if (stristr($param, "pageNum_Recordset1") == false && 
        stristr($param, "totalRows_Recordset1") == false) {
      array_push($newParams, $param);
    }
  }
  if (count($newParams) != 0) {
    $queryString_Recordset1 = "&" . htmlentities(implode("&", $newParams));
  }
}
$queryString_Recordset1 = sprintf("&totalRows_Recordset1=%d%s", $totalRows_Recordset1, $queryString_Recordset1);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Visualizar Ordens de Servi&ccedil;os em d&eacute;bitos</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
<!--
body,td,th {
	font-size: 12px;
}
body {
	background-color: #FFFFFF;
	margin-left: 0px;
	margin-top: 0px;
	margin-right: 0px;
	margin-bottom: 0px;
}
a:link {
	text-decoration: none;
}
a:visited {
	text-decoration: none;
}
a:hover {
	text-decoration: none;
}
a:active {
	text-decoration: none;
}
-->
</style></head>
<script src="scripts.js" type="text/javascript"></script>
<body>
<table width="100%" border="0" cellpadding="0" cellspacing=" 0">
  <tr>
    <td><table width="100%" border="0" align="center" style="background-color:#EEEEE6">
        <tr bgcolor="#FFFFCC">
          <td height="17" width="20" background="Imagens/bar_title.jpg" bgcolor="#FFCC00"><em><strong>OS</strong></em></td>
		  <td background="Imagens/bar_title.jpg" bgcolor="#FFCC00" align="center"><em><strong>Ed</strong></em></td>
		  <td background="Imagens/bar_title.jpg" bgcolor="#FFCC00" align="center"><em><strong>Vr</strong></em></td>
          <td background="Imagens/bar_title.jpg" bgcolor="#FFCC00" align="center"><em><strong>Cliente</strong></em></td>
          <td background="Imagens/bar_title.jpg" bgcolor="#FFCC00" align="center"><em><strong>Entrada</strong></em></td>
          <td background="Imagens/bar_title.jpg" bgcolor="#FFCC00" align="center"><em><strong>Func.</strong></em></td>
          <td background="Imagens/bar_title.jpg" bgcolor="#FFCC00" align="center"><em><strong>Equipamento</strong></em></td>
          <td background="Imagens/bar_title.jpg" bgcolor="#FFCC00" align="center"><em><strong>Marca</strong></em></td>
          <td background="Imagens/bar_title.jpg" bgcolor="#FFCC00" align="center"><em><strong>Entrega</strong></em></td>
          <td background="Imagens/bar_title.jpg" bgcolor="#FFCC00" align="center"><em><strong>Valor</strong></em></td>
        </tr>
        <?php do { ?>
          <tr>
            <td height="16" bgcolor="#FFCC00" align="center"><a href="javascript:openpopup('visualiza_osx.php?recordID=<?php echo $row_Recordset1['Cod_Equipamento']; ?>')" class="style17"> <?php echo $row_Recordset1['Cod_Equipamento']; ?></a> </td>
            <td style="background-color:#FFFFFF" align="center"><a href="javascript:openpopup('edd_os1_debito.php?recordID=<?php echo $row_Recordset1['Cod_Equipamento']; ?>')" title="Editar OS em d&eacute;bito de <?php echo $row_Recordset1['Cliente']; ?>"><img src="Imagens/fechar_os2.gif" width="15" height="15" border="0" /></a></td>
			<td style="background-color:#FFFFFF" align="center"><a href="javascript:openpopup('visualizaos_arquivox.php?recordID=<?php echo $row_Recordset1['Cod_Equipamento']; ?>')" title="Visualizar OS em d&eacute;bito de <?php echo $row_Recordset1['Cliente']; ?>"><img src="Imagens/s_vars.gif" width="15" height="15" border="0" /></a></td>
			<td style="background-color:#FFFFFF"><a href="javascript:openpopup('edd_os1.php?recordID=<?php echo $row_Recordset1['Cod_Equipamento']; ?>')"></a><a href="javascript:openpopup('visualiza_osx.php?recordID=<?php echo $row_Recordset1['Cod_Equipamento']; ?>')" class="style17" title="Valor da OS: R$ <?php echo $row_Recordset1['valor']; ?>"><?php echo $row_Recordset1['Cliente']; ?></a></td>
            <td style="background-color:#FFFFFF"><?php echo $row_Recordset1['Data_Entrada']; ?></td>
            <td style="background-color:#FFFFFF"><?php echo $row_Recordset1['Funcionario']; ?></td>
            <td style="background-color:#FFFFFF"><?php echo $row_Recordset1['Equipamento']; ?></td>
            <td style="background-color:#FFFFFF"><?php echo $row_Recordset1['Marca']; ?></td>
            <td style="background-color:#FFFFFF"><?php echo $row_Recordset1['Dataentrega']; ?></td>
            <td style="background-color:#FFFFFF"><?php echo $row_Recordset1['valor']; ?></td>
          </tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
            </table> 
	  <table border="0">
		<tr>
		  <td><?php if ($pageNum_Recordset1 > 0) { // Show if not first page ?><a href="<?php printf("%s?pageNum_Recordset1=%d%s", $currentPage, 0, $queryString_Recordset1); ?>"><img src="Imagens/First.gif" border="0" /></a><?php } // Show if not first page ?></td>
		  <td><?php if ($pageNum_Recordset1 > 0) { // Show if not first page ?><a href="<?php printf("%s?pageNum_Recordset1=%d%s", $currentPage, max(0, $pageNum_Recordset1 - 1), $queryString_Recordset1); ?>"><img src="Imagens/Previous.gif" border="0" /></a><?php } // Show if not first page ?>        </td>
		  <td><?php if ($pageNum_Recordset1 < $totalPages_Recordset1) { // Show if not last page ?><a href="<?php printf("%s?pageNum_Recordset1=%d%s", $currentPage, min($totalPages_Recordset1, $pageNum_Recordset1 + 1), $queryString_Recordset1); ?>"><img src="Imagens/Next.gif" border="0" /></a><?php } // Show if not last page ?>        </td>
		  <td><?php if ($pageNum_Recordset1 < $totalPages_Recordset1) { // Show if not last page ?><a href="<?php printf("%s?pageNum_Recordset1=%d%s", $currentPage, $totalPages_Recordset1, $queryString_Recordset1); ?>"><img src="Imagens/Last.gif" border="0" /></a><?php } // Show if not last page ?></td>
		</tr>
	  </table></td>
  </tr>
</table>

<p align="center"><font face="Times New Roman, Times, serif" size="6">Total a receber: R$ 
<?php
// Informações do Bando de Dados
$host      = "$hostname_data"; // IP ou localhost do servidor
$name_db   = "$database_data"; // Nome do Banco de Dados
$user_db   = "$username_data"; // Usuário
$pass_db   = "$password_data"; // Senha

$con = mysql_connect("$host","$user_db","$pass_db") or exit( mysql_error() ); // Conexão com o MySQL
mysql_select_db("$name_db",$con) or exit( mysql_error() ); // Seleção do Banco de Dados
$total = mysql_query("SELECT SUM(`valor`) as sumValor FROM `ordemservico`") or exit( mysql_error() ); // Som dos valores da coluna 'valor'

$result_total = mysql_result( $total, 0, 'sumValor' );
echo $result_total['sumValor']; // Impressão do resultado

?>
</font></p>

</body>
</html>
<?php
mysql_free_result($Recordset1);
?>
Observe o ultimo script PHP deste código, mais acima está a tabela que organiza a estrutura, nesta tabela tem algumas colunas sendo que, o ultimo script deste código é para somar os valores da coluna "valor", está dando certo.

Mas tem um pequeno probleminha, uma OS de 5 e outra de 4 ele soma e imprime 9, pois é, até aí tudo bem, mas, uma OS de 50 e uma de 40 ele continua mostrando 9.

Estou querendo saber o que há de errado neste script:
<p align="center"><font face="Times New Roman, Times, serif" size="6">Total a receber: R$ 
<?php
// Informações do Bando de Dados
$host      = "$hostname_data"; // IP ou localhost do servidor
$name_db   = "$database_data"; // Nome do Banco de Dados
$user_db   = "$username_data"; // Usuário
$pass_db   = "$password_data"; // Senha

$con = mysql_connect("$host","$user_db","$pass_db") or exit( mysql_error() ); // Conexão com o MySQL
mysql_select_db("$name_db",$con) or exit( mysql_error() ); // Seleção do Banco de Dados
$total = mysql_query("SELECT SUM(`valor`) as sumValor FROM `ordemservico`") or exit( mysql_error() ); // Som dos valores da coluna 'valor'

$result_total = mysql_result( $total, 0, 'sumValor' );
echo $result_total['sumValor']; // Impressão do resultado

?>
</font></p>
Será que tem alguma limitação de caractere? que mostra somente um caractere ao invés dele completo tipo, 50 + 40 = 90 ao invés de 50 + 40 = 9?

Se alguém puder me ajudar amigos, agradeço muito.

Abraços...

Aqui está o exemplo, o Total a receber não é este valor, mas, olha só o que ele mostra:
Posted Image
Este valor era pra ser R$ 590,00, mas, ele está mostrando 6, algo está erradno no script.
Tem alguém aqui no forum que possa me dar uma luz?

Agradeço...

IPB Skin By Virteq