php - 循环数据库结果,使用 number_format()

标签 php mysql loops mpdf

大家好,昨天开始使用 mpdf,它非常简单,但无法完成这项工作,所以我需要你们的帮助,请在下面发布我的所有问题:

在 Dreamweaver 的帮助下选择数据库:

mysql_select_db($database_valesilveira, $valesilveira);
$query_dados = sprintf("SELECT * FROM propostas, clientes, artigos, dados WHERE propostas.id_proposta = dados.id_proposta AND propostas.id_cliente = clientes.id_cliente AND artigos.id_artigo = dados.id_artigo AND propostas.id_proposta = %s ORDER BY posicao ASC", GetSQLValueString($colname_dados, "int"));
$dados = mysql_query($query_dados, $valesilveira) or die(mysql_error());
$row_dados = mysql_fetch_assoc($dados);
$totalRows_dados = mysql_num_rows($dados);

$colname_propostas = "-1";
if (isset($_GET['id_proposta'])) {
  $colname_propostas = $_GET['id_proposta'];
}

我如何循环这部分以显示数据库中的所有记录:

$articles = '
<div id="articles">
div class="wid10"><p>'.$row_dados['posicao'].'</p></div>
<div class="wid15"><p><img src="images/artigos/'.$row_dados['id_artigo'].'.png" style="height:60px;" /></p></div>
<div class="wid30"><p>'.$row_dados['desc'].'</p></div>
<div class="wid15"><p>'.$row_dados['unitario'].'</p></div>
<div class="wid15"><p>'.$row_dados['iliquido'].'</p></div>
<div class="wid10"><p>'.$row_dados['quantidade'].'</p></div>
</div>';

并在这部分使用 number_format() :

$total = '
<div id="total">
<p>Total iliquido: '.$row_dados['total_iliquido'].'</p>
<p>Subtotal Iliquido: '.$row_dados['subtotal'].'</p>
<p>Total: '.$row_dados['total'].'</p>
</div>';

其余代码:

include("mpdf.php");

$mpdf=new mPDF('c','A4','','',32,25,134,21,10,10); 

$mpdf->SetDisplayMode('fullpage');
$mpdf->SetHTMLHeader($header);
$mpdf->SetHTMLFooter($footer);

// LOAD a stylesheet
$stylesheet = file_get_contents('css/print.css');
$mpdf->WriteHTML($stylesheet,1);    // The parameter 1 tells that this is css/style only and no body/html/text

$mpdf->WriteHTML($articles);
$mpdf->WriteHTML($total);
$mpdf->Output();

exit;

就这些了,谢谢。

完整代码:

<?php require_once('Connections/valesilveira.php'); ?>
<?php 
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $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;
}
}

$colname_dados = "-1";
if (isset($_GET['id_proposta'])) {
  $colname_dados = $_GET['id_proposta'];
}
mysql_select_db($database_valesilveira, $valesilveira);
$query_dados = sprintf("SELECT * FROM propostas, clientes, artigos, dados WHERE propostas.id_proposta = dados.id_proposta AND propostas.id_cliente = clientes.id_cliente AND artigos.id_artigo = dados.id_artigo AND propostas.id_proposta = %s ORDER BY posicao ASC", GetSQLValueString($colname_dados, "int"));
$dados = mysql_query($query_dados, $valesilveira) or die(mysql_error());
$row_dados = mysql_fetch_assoc($dados);
$totalRows_dados = mysql_num_rows($dados);

$colname_propostas = "-1";
if (isset($_GET['id_proposta'])) {
  $colname_propostas = $_GET['id_proposta'];
}
mysql_select_db($database_valesilveira, $valesilveira);
$query_propostas = sprintf("SELECT id_proposta FROM propostas WHERE id_proposta = %s", GetSQLValueString($colname_propostas, "int"));
$propostas = mysql_query($query_propostas, $valesilveira) or die(mysql_error());
$row_propostas = mysql_fetch_assoc($propostas);
$totalRows_propostas = mysql_num_rows($propostas);
?>

<?php

$header = '
<div id="header">
<div id="left">
<p>Vale & Silveira, Lda</p>
<p>Rua Marques Da Alegrete Nº124 - A 4440-382 Sobrado</p>
</div>
<div id="right">
<div id="logo"><img src="images/valesilveira.png" style="margin-top:2px;" /></div>
<div id="proposta"><p>Proposta: '.$row_dados['id_proposta'].'</p></div>
</div>
</div>
<div id="userdata">
<p>Exmo.(s) Sr.(s)</p>
<p>'.$row_dados['nome'].'</p>
<p>'.$row_dados['empresa'].'</p>
<p>'.$row_dados['morada'].'</p>
</div>
<div id="body">
<p>Exm Senhores,</p>
<p>Conforme solicitado, vimos pela presente enviar a V. Exas, a nossa proposta nº '.$row_dados['id_proposta'].' , relativa a aquisição de equipamento hoteleiro, chamando desde já a V/ melhor atenção para os seguintes pontos:</p>

<p>1 - Prazo de entrega: A Combinar; </p>
<p>2 - Condições de pagamento: A Combinar;</p>
<p>3 - Garantia: 1 Ano contra defeitos de fabrico;</p>
<p>4 - Exclusões: excluem-se todos os trabalhos de contrução civil, redes de àgua, esgoto, gâs e electricidade.</p>
</div>

<div id="articlesHeader">

<div class="wid10"><p>Pos.</p></div>
<div class="wid15"><p>Imagem</p></div>
<div class="wid30"><p>Descrição</p></div>
<div class="wid15"><p>Valor Unitário</p></div>
<div class="wid15"><p>Valor Iliquido</p></div>
<div class="wid10"><p>Quant.</p></div>

</div>

';

$dados = mysql_query($query_dados, $valesilveira) or die(mysql_error());
# $totalRows_dados = mysql_num_rows($dados); # you don't need this unless you're using
                                   # $totalRows_dados somewhere else

# check for number of results. If there are none, exit / die / return / whatever
if (mysql_num_rows($dados) == 0) {
echo "no results found!";
# die / exit / return false / etc.
}

# initialise a string to hold the articles
$articles = '';

# loop through the results one at a time
while ($row_dados = mysql_fetch_assoc($dados)) {
# append the article div on to our existing string
$articles .= '<div id="articles">
div class="wid10"><p>'.$row_dados['posicao'].'</p></div>
<div class="wid15"><p><img src="images/artigos/'.$row_dados['id_artigo'].'.png" style="height:60px;" /></p></div>
<div class="wid30"><p>'.$row_dados['desc'].'</p></div>
<div class="wid15"><p>'.$row_dados['unitario'].'</p></div>
<div class="wid15"><p>'.$row_dados['iliquido'].'</p></div>
<div class="wid10"><p>'.$row_dados['quantidade'].'</p></div>
</div>';

// any other stuff you want to do to each piece of row data can go here

}


$footer = '

<div id="footer">
<div id="total"></div>
</div>
';


//==============================================================
//==============================================================
//==============================================================

include("mpdf.php");

$mpdf=new mPDF('c','A4','','',32,25,118,44,10,10); 

$mpdf->SetDisplayMode('fullpage');
$mpdf->SetHTMLHeader($header);
$mpdf->SetHTMLFooter($footer);

// LOAD a stylesheet
$stylesheet = file_get_contents('css/print.css');
$mpdf->WriteHTML($stylesheet,1);    // The parameter 1 tells that this is css/style only and no body/html/text

$mpdf->WriteHTML($html);

$mpdf->Output();

exit;
//==============================================================
//==============================================================
//==============================================================

?>


<?php
mysql_free_result($dados);

mysql_free_result($propostas);
?>

最佳答案

注意:mysql_* 函数已弃用,您应该迁移到 mysqli_* 或 PDO。

循环访问数据库查询结果的标准方法如下:

$dados = mysql_query($query_dados, $valesilveira) or die(mysql_error());
# $totalRows_dados = mysql_num_rows($dados); # you don't need this unless you're using
                                             # $totalRows_dados somewhere else

# check for number of results. If there are none, exit / die / return / whatever
if (mysql_num_rows($dados) == 0) {
    echo "no results found!";
    # die / exit / return false / etc.
}

# initialise a string to hold the articles
$articles = '';

# loop through the results one at a time
while ($row_dados = mysql_fetch_assoc($dados)) {
    # append the article div on to our existing string
    $articles .= '<div id="articles">
    div class="wid10"><p>'.$row_dados['posicao'].'</p></div>
    <div class="wid15"><p><img src="images/artigos/'.$row_dados['id_artigo'].'.png" style="height:60px;" /></p></div>
    <div class="wid30"><p>'.$row_dados['desc'].'</p></div>
    <div class="wid15"><p>'.$row_dados['unitario'].'</p></div>
    <div class="wid15"><p>'.$row_dados['iliquido'].'</p></div>
    <div class="wid10"><p>'.$row_dados['quantidade'].'</p></div>
    </div>';

    // any other stuff you want to do to each piece of row data can go here

}

对于第二部分,只需对要格式化的任何数字调用 number_format 即可。如果您look at the documentation,这是非常不言自明的。 。示例:

$text = '<p>Total iliquido: '. number_format( $row_dados['total_iliquido'] ) .'</p>';

关于php - 循环数据库结果,使用 number_format(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26325485/

相关文章:

mysql - 不允许主机 x 连接到此 mysql 服务器

mysql - 创建存储过程 - MySQL

java - Android:使用循环用图像 ID 填充数组

python - 如何在 for 循环迭代中更改多个变量

php - 根据用户选择创建 8 个具有独特 HTML 标签的变量

php - 上传前如何使用php获取安全文件名

php - php 中每天细菌计数的输出循环

php - 获取查询中数据库存储号码的前 5 位数字

php - 为什么 JQWidget 在过滤时显示内部服务器错误 500?

php - 在这种情况下如何使用比较