PHP中的循环错误

时间:2016-10-29 07:40:31

标签: php mysql

我有此代码将数据添加到MySQL中。

$arr = array("Dr APJ Abdul Kalam", "Benjamin Franklin", "Albert Einstein", "Mahatma Gandhi", "Abraham Lincoln", "Gen. Patton", "Stephen Hawking", "Mark Twain", "George Washington");
foreach ($arr as &$value) {
$sql="UPDATE ci_thought SET text='".$value."'";
If ($this->db->query($sql) === TRUE) {
    echo "added ".$value;
} else{
    echo "ERROR";
}
}

它正在做的是更新行文本,但所有值都是乔治华盛顿。
我有366行,并希望在循环中添加这9个,以便在每9个不同的条目后,此代码再次运行,直到插入了366个值。

请帮助使代码正确

2 个答案:

答案 0 :(得分:1)

我使用以下代码解决了问题

    $arr = array(   "Dr APJ Abdul Kalam",
                    "Benjamin Franklin",
                    "Albert Einstein",
                    "Mahatma Gandhi",
                    "Abraham Lincoln",
                    "Gen. Patton",
                    "Stephen Hawking",
                    "Mark Twain",
                    "George Washington"
    );
for($i= 1; $i <=366;) {
foreach ($arr as &$value){

$sql="UPDATE ci_thought SET text='".$value."' WHERE id=".$i;
If ($this->db->query($sql) === TRUE) {
    echo $i.". added ".$value."<br>";
} else{
    echo "ERROR";
}
$i++;
}

} 我做的是我添加循环。
我在$i=1;分配了$i <= 366并修复了小于或等于366的值,我正在按for语句循环,并将{i}的值递增i++没有其他更改完成了!

编辑更改

此代码现在正常工作......我正在添加一个额外的i++,现在已经修复了,而且运行得很好。对不起任何拼写,语法错误和重复发帖:(

答案 1 :(得分:-2)

    <?php

        $arr = array(   "Dr APJ Abdul Kalam",
                        "Benjamin Franklin",
                        "Albert Einstein",
                        "Mahatma Gandhi",
                        "Abraham Lincoln",
                        "Gen. Patton",
                        "Stephen Hawking",
                        "Mark Twain",
                        "George Washington"
        );
        // IF  YOU WANT TO UPDATE THE text COLUMN OF ALL RECORDS
        // YOU MAY FIRST NEED TO GET THEIR ID
        $idSQL  = 'SELECT id FROM ci_thought';
        $ids    = $this->db->query($sql);
        $key    = 0;
        var_dump($ids); 
        exit;

        // ASSUMING $ids IS AN ARRAY OF OBJECTS WITH id KEY,
        // YOU CAN USE THE IDS FOR THE UPDATED
        foreach ($ids as $index=>$data) {               
            if($index%9 == 0){
                $key    = 0;                    
            }
            $id     = $data->id;
            $sql    = "UPDATE ci_thought SET text='". $arr[$key] ."' WHERE id='{$id}'";
            if ($this->db->query($sql) === TRUE) {
                echo "added ".$value;
            } else{
                echo "ERROR";
            }
            $key++;
        }