【问题标题】:while loop to update dates in DB only updates first row?while 循环更新数据库中的日期只更新第一行?
【发布时间】:2010-11-17 10:32:43
【问题描述】:

我不知道为什么这不起作用。


function query($sql) {

     $this->result = @mysql_query($sql, $this->conn);

     return($this->result != false);

}

function convert() { $this->db->open(); $sql_update = ""; $this->db->query("SELECT * FROM ACCOUNTS "); $str = ''; while ($row = $this->db->fetchassoc()) { $jobNum = $row['JOBNUMBER']; $old_date = $row['INSTALLDATE']; $new_date = date("Y-m-d", strtotime($old_date)); $sql_update = "UPDATE ACCOUNTS SET INSTALLDATE='$new_date' WHERE JOBNUMBER='$jobNum' "; //$this->db->query($sql_update) or die($this->response->throwResponseError(MSG_DATABASE_ERROR . mysql_error())); $str .= $jobNum . " -- " . $new_date . "
"; }

    return $str;
}

如果我在注释掉该行的情况下运行它,它会返回我想要的所有结果。但是当我取消注释它实际运行更新的行时,它会更新第一条记录并停止循环。为什么?

【问题讨论】:

    标签: php mysql loops


    【解决方案1】:

    当您运行更新时,它会使您的 db 中的隐藏语句处理程序以及与之关联的结果无效。

    db->query("SELECT …") -- creates the handler
    
    -- 1st iteration
    db->fetchassoc() -- fetches the first row
    db->query("UPDATE …") -- creates another handler and destroys the old one
    
    -- 2nd iteration
    db->fetchassoc() -- no rows returned by `UPDATE`, nothing to fetch
    

    您正在尝试做的事情,可以使用单个语句更轻松地完成:

    UPDATE  accounts
    SET     installed = DATE_FORMAT(STR_TO_DATE(installed, @current_format_string), '%Y-%d-%m')
    

    ,其中@current_format_string 是您现在的日期格式。

    更新:

    尝试运行此查询:

    UPDATE  accounts
    SET     installdate = DATE_FORMAT(STR_TO_DATE(installdate , '%m/%d/%Y'), '%Y-%d-%m')
    

    在运行UPDATE 查询之前,您可能需要使用SELECT 检查结果:

    SELECT  DATE_FORMAT(STR_TO_DATE(installdate, '%m/%d/%Y'), '%Y-%d-%m')
    FROM    accounts
    

    【讨论】:

    • 所以我最好将所有变量推入一个数组然后为每个变量做一个?或者我该如何解决?
    • 完美。老实说,我花了几个小时,看不出有什么干扰。非常感谢!
    • @mlebrun15: 真正更好的是你在MySQL 一侧进行操作,如帖子所示。
    • 它不断将值设置为空。您的 var “已安装”,应该与列名相同吗?
    • 是的。您现在可以发布一些包含在表格中的行吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    相关资源
    最近更新 更多