我想在下面的代码中使用foreach进行循环而不是while循环。但由于某种原因,foreach循环不能像我预期的那样工作。请帮我解决这个问题。
class MyDB extends SQLite3
{
function __construct()
{
$this->open('test.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$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'] ."\n\n";
}
echo "Operation done successfully\n";
$db->close();
这是我使用的代码。
$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'] ."\n\n";
}
echo "Operation done successfully\n";
$db->close();
答案 0 :(得分:1)
也许我迟到了,但无论如何
foreach 样本
foreach ($ret->fetchArray(SQLITE3_ASSOC) as $row) {
echo "<pre>";
$array[] = $row;
}
echo $array[0] ."\n";
echo $array[1] ."\n";
echo $array[2] ."\n";
答案 1 :(得分:0)
这段代码对我有用。
$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 successfully\n";
$db->close();
foreach($data as $val){
echo $val['id'].'<br>'.$val['address'].'<br>'.$val['salary'].'<br>';
}
答案 2 :(得分:0)
我认为不适用于 SQlite3 类,但使用 PDO...
$db = new PDO('sqlite:(your path)test.db');
$sql =<<<EOF
SELECT * from COMPANY;
EOF;
$ret = $db->query($sql);
foreach($ret as $row){
echo "ID = ". $row['ID'] . "\n";
echo "NAME = ". $row['NAME'] ."\n";
echo "ADDRESS = ". $row['ADDRESS'] ."\n";
echo "SALARY = ".$row['SALARY'] ."\n\n";
}
SQlite3 类也不适用于 Laravel。 PDO 有效。我使用的是 PHP 8 和 Laravel 8。
我在哪里找到的:https://www.a2hosting.com.br/kb/developer-corner/sqlite/connect-to-sqlite-using-php