douchen1988
2014-02-12 23:34
浏览 46
已采纳

从查询中仅获取1个结果 - 将结果保存在CSV文件中

I have been dealing with this all day ... I am doing a SQL Query and it suppose to return several rows, but I am only getting one, I would believe it is the first one, I want to save these results/rows in a CSV file.

So when I do the var_dump only one result is showing and I can only write that first line in the CSV file.

session_start();

$file = 'file.csv';

if(isset($_POST['button1'])){

echo("You clicked button one!");

$con=mysqli_connect("localhost","root","","test");

$query = "SELECT * FROM test.tec_milenio_cubo";
$result = mysqli_query($con, $query); // EJECUTAS LA CONSULTA
$row = mysqli_fetch_assoc($result);


var_dump ($row);


$_SESSION['file'] = $file;

$fp = fopen($file, 'w');

foreach ($row as $value) {

    fputcsv($fp, $value);

}

fclose($fp);
mysqli_close($con);

图片转代码服务由CSDN问答提供 功能建议

我整天都在处理这个...我正在做一个SQL查询,它假设要返回几行 ,但我只得到一个,我相信它是第一个,我想将这些结果/行保存​​在CSV文件中。

所以当我执行var_dump时只有一个结果 正在显示,我只能在CSV文件中写第一行。

  session_start(); 
 
 $ file ='file.csv'; 
 
if  (isset($ _ POST ['button1'])){
 
echo(“你点击了一个按钮!”); 
 
 $ con = mysqli_connect(“localhost”,“root”,“”,“test”  ); 
 
 $ query =“SELECT * FROM test.tec_m​​ilenio_cubo”; 
 $ result = mysqli_query($ con,$ query);  // EJECUTAS LA CONSULTA 
 $ row = mysqli_fetch_assoc($ result); 
 
 
var_dump($ row); 
 
 
 $ _SESSION ['file'] = $ file; 
 
 $ fp  = fopen($ file,'w'); 
 
foreach($ row as $ value){
 
 fputcsv($ fp,$ value); 
 
} 
 
 nclclose($ fp);  
mysqli_close($ con); 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanhan5230 2014-02-12 23:39
    已采纳

    Use a while loop on your $row.

    $fp = fopen($file, 'w');
    
    while ($row = mysql_fetch_array($result)) {
        var_dump ($row);
        fputcsv($fp, $row);
    }
    
    fclose($fp);
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douyue1481 2014-02-12 23:43

    Quixrick is correct.

    Your initial code is only pulling one record from the database at a time.

    The while loop will continue until all records are pulled and end when $row is not assigned a value.

    Happy Coding :-)!

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题