PHP中的$ _POST到CSV

时间:2016-12-08 12:13:41

标签: php csv

我有一个php文件将php数据导出到csv。

但我有以下错误

  

警告:mysql_num_fields()期望参数1是资源布尔值,在 C:\ xampp \ htdocs \ exporttocsv3 \ export2csv.php 28 < / b>

  

警告:mysql_fetch_array()期望参数1为    40

C:\ xampp \ htdocs \ exporttocsv3 \ export2csv.php 中给出的资源布尔值

form.php的

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<form method="post" action="export2csv.php">
    <input type = "text" name ="wow" placeholder="Search by name">
<button  name="submit" type="submit">Wew</button>
</form>

</body>
</html>

export2csv.php

<?php

// Database Connection

$host="localhost";
$uname="root";
$pass="louchin";
$database = "phppot_examples";  

$connection=mysql_connect($host,$uname,$pass); 

echo mysql_error();

//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or die("Database could not be selected");  
$result=mysql_select_db($database)
or die("database cannot be selected <br>");



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

$name = $_POST['wow'];

$output = "";
$table = "toy"; 
$sql = mysql_query("SELECT id, name, code FROM $table WHERE (name LIKE '%$name%'");
$columns_total  = mysql_num_fields($sql);

// Get The Field Name

for ($i = 0; $i < $columns_total; $i++) {
    $heading    =   mysql_field_name($sql, $i);
    $output     .= '"'.$heading.'",';
}
$output .="\n";

// Get Records from the table

while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}

// Download the file

$filename =  "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $output;
exit;
}   
?>

正如你可以看到它在mysql中但我稍后会将其转换为mysqli查询。感谢您将来的答案

1 个答案:

答案 0 :(得分:0)

您的查询中缺少近似括号。这就是它显示错误的原因。

 $sql = mysql_query("SELECT id, name, code FROM $table WHERE (name LIKE '%$name%')")