Skip to content
Advertisement

Foreach loop not working for sqllite in php

I want to use foreach for looping instead of while loop in the below code. But for some reason the foreach loop is not working as I expected. Can please help me with this.

class MyDB extends SQLite3
 {
  function __construct()
  {
     $this->open('test.db');
  }
  }
  $db = new MyDB();
  if(!$db){
  echo $db->lastErrorMsg();
  } else {
  echo "Opened database successfullyn";
  }

  $sql =<<<EOF
  SELECT * from COMPANY;
  EOF;
  $ret = $db->query($sql);
  $newArray = array_chunk($links['data'], 12, false);
  while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
  echo "ID = ". $row['ID'] . "n";
  echo "NAME = ". $row['NAME'] ."n";
  echo "ADDRESS = ". $row['ADDRESS'] ."n";
  echo "SALARY =  ".$row['SALARY'] ."nn";
  }
  echo "Operation done successfullyn";
  $db->close();

THis is the code I Used.

$ret = $db->query($sql);
$value = $ret->fetchArray(SQLITE3_ASSOC);
foreach($value as $row){
  echo "ID = ". $row['ID'] . "n";
  echo "NAME = ". $row['NAME'] ."n";
  echo "ADDRESS = ". $row['ADDRESS'] ."n";
  echo "SALARY =  ".$row['SALARY'] ."nn";
}
echo "Operation done successfullyn";
$db->close();

Advertisement

Answer

This piece of code worked for me.

  $sql =<<<EOF
  SELECT * from COMPANY;
  EOF;
  $ret = $db->query($sql);
  while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
  $data[]=array('id'=>$row['ID'],'name'=>$row['NAME'],'address'=>$row['ADDRESS'],'salary'=>$row['SALARY']);
  }
  echo "Operation done successfullyn";
  $db->close();
  foreach($data as $val){
 echo $val['id'].'<br>'.$val['address'].'<br>'.$val['salary'].'<br>';
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement