Question

I am trying to create an array containing results from an SQL table. But my foreach loop does not appear to be function correctly.

Here is my code: $stmt->bind_param("i", $id); $stmt->execute(); while ($stmt->fetch()) { } $stmt->close();

    $i = 0;
    foreach ($connected_items as &$value) {
            print_r ($connected_items[$i]);
            $stmt->bind_param("i", $connected_items[$i]);
            $stmt->execute();
            while ($stmt->fetch()) {
                $result[] = array(,
                        );
            }
            $stmt->close();

            $i++;
            }
    unset($value);
    )
)

It appears to be running the for loop on my print statement and then MySQL statement, using the last connected_items_id, why is that? And why is it not returning the associated values for that id?

Was it helpful?

Solution

remove this [] at line number 6:

while ($stmt->fetch()) {
    $connected_items = array($connected_items_id);
}

instead of this:

while ($stmt->fetch()) {
    $connected_items[] = array($connected_items_id);
}

OTHER TIPS

Try this,

"connected_item_id" => $connected_items[0],

instead of

"connected_item_id" => $connected_items_id,

Try

foreach ($connected_items as $value) {
 ......................
 ......................
 $stmt = $this->db->prepare('SELECT name, serial FROM `glpi_monitors` WHERE id =?');
 $stmt->bind_param("i", $value[0]);
 ................................
 ................................
}

Also you can use IN keyword instead of looping and querying each time.

 $sql = "SELECT name, serial FROM `glpi_monitors` WHERE id IN('".implode("','",$connected_items)."'");
 $stmt = $this->db->prepare($sql);

eg :

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top