为什么我只收到数组每个元素的第一个值


Why am I receiving only the first value for each element of the array?

我无法弄清楚为什么我的所有结果都是它返回的第一个值的重复。

此代码返回相同的 ID 和格式化日期,一遍又一遍地重复;但是,我希望它读取一个值,然后为数据库中的每个条目转换该值。 这是我的代码:

<?php
include('../includes/conn.inc.php');
$stmt = $mysql->prepare("SELECT id, endDate FROM TABLE ORDER BY id");
$stmt->execute();
$stmt->bind_result($id, $endDate);
while($row = $stmt->fetch()) {
    $dataRow[] = array('id'=>$id,'endDate'=> $endDate);
};
foreach($dataRow as $i) {
    $newEndDate = date('Y-m-d',strtotime($endDate));
    $sql = 'UPDATE TABLE SET startDate = ? WHERE id= ? ';
    $stmt = $mysql->stmt_init();
    if ($stmt->prepare($sql)) { 
        $stmt->bind_param('si',$newEndDate, $id);
        $OK = $stmt->execute();}
        if ($OK) {
            echo $id . " " . $newEndDate .  "done <br/>";
        } else {
            echo $stmt->error;
        } 
        $stmt->close();
    };  

foreach中,您始终使用从上一个$stmt->fetch()设置的最后一个值

尝试:

foreach($dataRow as $i) {
    $newEndDate = date('Y-m-d',strtotime($i['endDate']));
    $id = $i['id'];
    $sql = 'UPDATE TABLE SET startDate = ? WHERE id= ? ';
    $stmt = $mysql->stmt_init();
    if ($stmt->prepare($sql)) { 
        $stmt->bind_param('si',$newEndDate, $id);
        $OK = $stmt->execute();
    }
    if ($OK) {
        echo $id . " " . $newEndDate .  "done <br/>";
    } else {
        echo $stmt->error;
    } 
    $stmt->close();
}; 

使用get_result();

$dataRow = array()
$stmt = $mysql->prepare("SELECT id, endDate FROM TABLE ORDER BY id");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_array()) {
    $dataRow[$row['id']] = $row['endDate'];
}

并且您不会在第二个循环中填充$endDate

foreach($dataRow as $i => $endDate){
    $newEndDate = date('Y-m-d',strtotime($endDate));
    ... // rest of your code