循环访问数据库并使用foreach循环更新字段

时间:2015-08-04 13:05:09

标签: php mysql

我正在尝试从表中舍入小数并使用新的舍入值更新同一个表中的另一个字段,但我似乎无法破解它。

舍入脚本运行完美,但我不得不尝试运行舍入脚本并相应地更新数据库。

该表包含10,000多个条目,因此我只请求特定给定日期的数据,一次缩小到大约1,200个条目......

这是我的foreach循环(它自己运行良好),但这不起作用:

<?php
include("XXXX");
$cxn = mysqli_connect($host,$user,$password,$dbname)
    or die ("Couldn't connect to server.");
$query = "SELECT `sub_hrs`, `id` FROM `attend` WHERE `date` = '$date'";
$result = mysqli_query($cxn,$query)
    or die ("Couldn't execute query.");

while($row = mysqli_fetch_assoc($result))
{
    extract($row);  
    $n = array($sub_hrs);
    foreach($n as $i) {
        $new[] = (fmod($i, 1) > 0.5 
                ? sprintf("%2.f", (float) (int) $i + 0.5) 
                : sprintf("%2.f", (float) (int) $i)) . PHP_EOL; 
        $mysql_query("UPDATE `attend` SET `total_hrs` = $new WHERE `id` = $id");
        }
}

2 个答案:

答案 0 :(得分:0)

您正在下面的行中分配一个数组$ new [。

  $new[] = (fmod($i, 1) > 0.5 
            ? sprintf("%2.f", (float) (int) $i + 0.5) 
            : sprintf("%2.f", (float) (int) $i)) . PHP_EOL; 

但是在查询中你只传递$ new变量,因为你不会在$ new变量中得到任何值。

    $mysql_query("UPDATE `attend` SET `total_hrs` = $new WHERE `id` = $id");

答案 1 :(得分:0)

Thanx对所有帮助人员,但我发现一个简单的查询可以解决这个问题......

UPDATE `attend`
            SET `total_hrs` = if((`sub_hrs` - truncate(`sub_hrs`,0)) < 0.5, truncate(`sub_hrs`,0), ((truncate(`sub_hrs`,0)) + 0.5))
            WHERE `date` = '$date'
相关问题