user2030570
user2030570

Reputation: 3

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

I am not able to figure out why all of my results are repetitions of the first values it returns.

This code returns the same ID and formatted date repeated over and over again; however, I was expecting it to read a value and then transform that value for each entry in the DB. Here is my code:

<?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();
    };  

Upvotes: 0

Views: 108

Answers (2)

In your foreach you are always using the last values that were set from the last $stmt->fetch()

Try:

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();
}; 

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157839

use 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'];
}

and you don't populate your $endDate in the second loop

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

Upvotes: 0

Related Questions