0

我的代码有问题,问题是数据未更新仍然为 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";
    }
4

2 回答 2

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]."'");
}

结果完美!

谢谢大家

于 2013-11-15T03:19:03.427 回答
0

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

检查这个:

$arr[] = $arrs[0];

这现在保存了结果集的第一条记录。预计只有一条现金 >= 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");
    }

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

于 2013-11-14T14:48:18.550 回答