将mysql for循环转换为mysqli for循环

时间:2015-09-07 18:28:39

标签: php mysql mysqli

我在互联网上发现了一段完全符合我要求的代码。代码是关于使用PHP mysql将mysql数据下载到excel表格式。

问题是我需要将mysql转换为mysqli函数,它似乎不起作用。 for循环需要完全改变。有什么建议吗?

$conn = mysqli_connect("localhost","root","","dvarsam2"); //server,username,password,db
mysqli_query($conn,'SET NAMES utf8');

$setCounter = 0;

$setExcelName = "download_excal_file";

$setSql = "SELECT * FROM wp_applications";

$setRec = mysqli_query($conn,$setSql);

$setCounter = mysql_num_fields($setRec);

for ($i = 0; $i < $setCounter; $i++) {
    $setMainHeader .= mysql_field_name($setRec, $i)."\t";
}

while($rec = mysql_fetch_row($setRec))  {
  $rowLine = '';
  foreach($rec as $value)       {
    if(!isset($value) || $value == "")  {
      $value = "\t";
    }  else  {
//It escape all the special charactor, quotes from the data.
      $value = strip_tags(str_replace('"', '""', $value));
      $value = '"' . $value . '"' . "\t";
    }
    $rowLine .= $value;
  }
  $setData .= trim($rowLine)."\n";
}
  $setData = str_replace("\r", "", $setData);

if ($setData == "") {
  $setData = "\nno matching records found\n";
}

$setCounter = mysql_num_fields($setRec);



//This Header is used to make data download instead of display the data
 header("Content-type: application/octet-stream");

header("Content-Disposition: attachment;      filename=".$setExcelName."_Reoprt.xls");

header("Pragma: no-cache");
header("Expires: 0");

//It will print all the Table row as Excel file row with selected column name as header.
echo ucwords($setMainHeader)."\n".$setData."\n";

2 个答案:

答案 0 :(得分:1)

您也可以修改SELECT语句,以Excel格式格式化输出:

SELECT * FROM mytable
INTO OUTFILE '/mytable.csv'
FIELDS ESCAPED BY '""'
TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n';

有关详情,请参阅here。您提供的代码来自接受的答案,但我更喜欢这个解决方案。

答案 1 :(得分:1)

对于MySQLi:

<?php

$conn = mysqli_connect("localhost","root","","dvarsam2"); //server,username,password,db
mysqli_query($conn,'SET NAMES utf8');

$setExcelName = "download_excal_file";

//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");

header("Content-Disposition: attachment;      filename=".$setExcelName."_Reoprt.xls");

header("Pragma: no-cache");
header("Expires: 0");

$result = mysqli_query( $conn, "SELECT * FROM wp_applications" );

$i = 0;

while( $row = $result->fetch_assoc() )
{
  if( $i == 0 )
  {
    // Print field names
    foreach( $row as $key => $value )
    {
      echo $key."\t";
    }

    echo "\n";
  }

  // Print data
  foreach( $row as $key => $value )
  {
    $value = strip_tags(str_replace('"', '""', trim($value)));
    echo '"' . str_replace("\r", "", $value ) . '"' . "\t";
  }

  echo "\n";

  $i++;
}

if( $result->num_rows == 0 ) echo "no matching records found\n";
相关问题