获取实际字段名称和值:简化版本

时间:2013-02-20 07:59:29

标签: php mysql mysqli

假设我有3个表:Standard_Code和Report and Transactions。

  

Standard_Code 表格字段名称:代码

     

值为:Opening_Balance,Ending_Balance,Actual_Remaining_Balance

     

报告表字段名称:Opening_Balance,Ending_Balance,Actual_Remaining_Balance

你可能会想我为什么要做这种重复?好吧,从技术上来说它们是不同的,因为'Standard_Code'表有行值,但在我的'Report'中它们是列,它们是固定的,不能更改。

  

$ sql =“选择t.code,t.amount来自Transactions t Inner Join Standard_Code sc on   t.code = sc.code“;

     

$ result = mysql_query($ sql);

     

while($ row = mysql_fetch_assoc($ result)){

    foreach ($row as $col => $val) {
        echo $col." = ".$val."<br />";        
}
     

sqlQuery =“更新报告集”。 fieldname 。 “'=”。 ;

}

据说,在while或foreach循环期间,如何执行此查询以更新Report表:

来自Standard_Code表

fieldname Code值(此处的值是报表的实际字段名称)

:来自交易表:Amount

根据我的要求,我不知道如何工作。

我的理由:我有特殊要求处理报告,特别是关于价值放置/格式化等等。简而言之,报告很复杂,这就是为什么我创建自定义报告表以便我可以轻松获取报告数据格式。

2 个答案:

答案 0 :(得分:1)

$sql = "Select t.code, t.amount From Transactions t Inner Join Standard_Code sc on t.code = sc.code";

$result = mysql_query($sql);
$q = array();

while($row = mysql_fetch_assoc($result)) {
  $q[] = $row['code'].' = '.$row['amount'];    
}
// UPDATE report SET Opening_Balance = 2, Ending_Balance = 2, Actual_Remaining_Balance = 2
mysql_query('UPDATE Report SET '.join(', ', $q));

答案 1 :(得分:0)

嗯,我理解你的情况,因为你想在循环事务时更新每种code类型的总和。这是我的代码(我们不应该再使用mysql_ api,而是使用PDO代替

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');

$stmt = $db->prepare("Select t.code, t.amount From Transactions t Inner Join Standard_Code sc on t.code = sc.code");
if ($stmt->exectute())
{
    $rows = $stmt->fetchAll();
    foreach($rows as $row)
    {
        $stmt = "Update Report Set `" . $row['code'] . "` = `" . $row['code'] . "` + :val";   
        $stmt->bindValue(":val", $row['amount']);
        $stmt->execute();
    }
}

在这种情况下,您的report表格只有一个行。您还可以将此代码修改为插入新行,而不是更新旧记录。但是,如果使用此方法,则需要一个额外的主键列。