我无法弄清楚为什么我的所有结果都会重复它返回的第一个值。
此代码返回相同的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();
};
答案 0 :(得分: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();
};
答案 1 :(得分: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