0

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

此代码返回相同的 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();
    };  
4

2 回答 2

1

在你的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();
}; 
于 2013-02-01T14:54:51.667 回答
0

利用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
于 2013-02-01T14:59:27.707 回答