且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PDO更新具有多个数组的SQL表

更新时间:2023-01-23 09:27:53

是的,SQL参数从1开始编号(我不知道为什么该答案的所有者删除了它).

It's true, SQL parameters start numbering from 1 (I don't know why the owner of that answer deleted it).

参数编号是在SQL/CLI标准中定义的,该标准可以追溯到1980年代,当时发明了零号. ;-)

The parameter numbering is defined in the SQL/CLI standard, which dates back to the 1980's, before the number zero was invented. ;-)

至于为什么您的代码没有更新,我希望确保id值位于您期望的位置.反转并分块数组后,如果id值未在正确的位置结束,则它可能会尝试更新行,但不匹配任何行.

As for why your code isn't updating, I'd look to make sure the id values are positioned where you expect them. After reversing and chunking the array, if the id value doesn't end up in the right spot, it might try to update rows, but match none.

这是编写此例程的另一种方法:

Here's an alternative way to code this routine:

$backwards = array_reverse($update);
$chunks = array_chunk($backwards, 7);

var_dump($chunks[1]);       

try {
    $update_project = $db->prepare('
        UPDATE projects
        SET comments = ?,
            contact = ?,
            est_end = ?,
            est_start = ?,  
            apm = ?,  
            pm = ?                              
        WHERE id = ?
    ');
    $n = 0;
    foreach ($chunks as $chunk) {
        $update_project->execute($chunk);
        $n += $update_project->rowCount();
    }   

    echo 'Projects Updated, affected $n rows';        

} catch(PDOException $e) {
    die($e->getMessage());
}