gpt4 book ai didi

php - 使用php导出sqlite表

转载 作者:行者123 更新时间:2023-12-02 04:19:23 25 4
gpt4 key购买 nike

我刚刚开始使用 PHP,我需要将一个表从我的 sqlite 数据库导出到 CSV 或理想情况下的 XLS。我找到了一个使用 mysql 的示例,但我无法将其转换为与 sqlite 一起使用。

这是我到目前为止所拥有的:

<?php
$db = new PDO('sqlite:../ccm.sqlite');
$query = $db->query('SELECT * FROM Emails');
$export = sqlite_query ($query);
$fields = sqlite_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ ){
$header .= sqlite_field_name( $export , $i ) . "\t";
}

while( $row = sqlite_fetch_row( $export ) ){
//sqlite_fetch_row doesnt actually exist...
$line = '';
foreach( $row as $value ){
if ( ( !isset( $value ) ) || ( $value == "" ) ){
$value = "\t";
}else{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );

if ( $data == "" ){
$data = "\n(0) Records Found!\n";
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=emails.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>

有人可以帮我解决这个问题吗?或者如果有一种更简单的方法那就太好了。干杯

最佳答案

您正在将 PDO 方法与 sqlite_* 函数混合;尝试使用其中之一:

$db = new PDO("sqlite:../ccm.sqlite");
$query = $db->query("select * from emails");
$first_row = true;
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
if ($first_row)
{
// I'm not sure how to get the field names using a PDO method but
// we can use the first row's (or any row's) key values as these
// are the field names.
$first_row = false;
$number_of_fields = count($row);
$field_names = array_keys($row);
$first_field_name = $field_names[0];
}
// do stuff here with the row
print_r($row);
}

$db = sqlite_open("../cmm.sqlite");
$query = sqlite_query($db, "select * from emails");
$number_of_fields = sqlite_num_fields($query);
$first_field_name = sqlite_field_name($query, 0);
while ($row = sqlite_fetch_array($query))
{
// do stuff here with the row.
print_r($row);
}

我不是 100% 确定,但我认为 PDO 适用于 sqlite3 数据库,而 sqlite_* 函数适用于 sqlite2 数据库。

关于php - 使用php导出sqlite表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3986469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com