从具有不同值的数组更新表,其中空字段

时间:2013-11-14 14:31:29

标签: php mysql

我的代码有问题,问题是数据不更新仍为NULL。

表A

year | period | code | user_id 
2013 |      4 | 1231 | 
2013 |      4 | 1232 |
2013 |      4 | 1233 |
2013 |      4 | 1234 |
2013 |      4 | 1235 |

表B

user_id | user_name | cash
A1      | AB        |   10
A2      | BC        |    5
A3      | CD        |    7

当现金> = 7

时,我会将表B user_id放到表A user_id

表格结果

year | period | code | user_id 
2013 |      4 | 1231 |      10
2013 |      4 | 1232 |       7
2013 |      4 | 1233 |
2013 |      4 | 1234 |
2013 |      4 | 1235 |

这是我的代码,

    $arr = array();
    $query = mysql_query("select user_id from tableB where cash >= 7");
    while ($arrs = mysql_fetch_array($query)) {
            $arr[] = $arrs[0];
            }
    $count = count($arr);
    for ($i = 0; $i < $count; $i++) {
        $sql = mysql_query("UPDATE tableA SET user_id ='$arr[$i]' WHERE year = 2013 and period = 4 and user_id IS NULL");
    }
    if ($sql) {
        echo "success";
    }

2 个答案:

答案 0 :(得分:0)

查询中的运算符应为>=而不是=>

检查:

$arr[] = $arrs[0];

现在保存结果集的第一条记录。预计只有一个现金&gt; = 7的记录,这可能没问题,但这是一个冒险的假设。

for ($i = 0; $i < $count; $i++) {
        $sql = mysql_query("UPDATE tableA SET user_id ='$arr[$i]' WHERE year = 2013 and 
                            period = 4 and user_id IS NULL");
    }

在这里$arr[$i]遍历第一条记录的字段,按顺序为您提供值“A3”,“CD”和7,并且您在表上运行了三个无用的更新。之后,表A中的列user_id的值为7而不是'A3',因为这是循环中的最后一个值。

答案 1 :(得分:0)

我的代码解决方案

$arr = array();
$query = mysql_query("select user_id from tableB where cash >= 7");
while ($arrs = mysql_fetch_array($query)) {
        $arr[] = $arrs[0];
        }
$q = mysql_query("select code from tableA order by code");

    $index = 0;
    while($codes = mysql_fetch_row($q)){
    $sql = mysql_query("UPDATE tableA SET user_id ='".$arr[$index++]."' WHERE code='".$codes[0]."'");
}

结果完美!

感谢所有