我正在尝试根据用户的需求将特定记录输出到.csv中。到目前为止,我能够让 .csv 工作,但现在我试图从表单中获取记录,我不断收到消息,表明它无法获取我的 sql 记录。
是的,您可能会说将我的 php 代码放在页面顶部可能会出现问题,但我将其放在那里的原因是为了避免将 html 标记也打印到 .csv 文件中。
这是我当前的代码:
<?php
if(isset($_POST['submit']))
{
$material = $_POST['materials'];
mysql_connect('localhost', 'root', 'pw');
mysql_select_db ("db");
$result = mysql_query("SELECT " . $material . " FROM materials");
if (!$result)
die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
}
?>
<h1>Generate Reports</h1>
<form enctype="multipart/form-data" action="create" method="post">
<table>
<tr>
<td><strong>Materials</strong></td>
<?php
mysql_connect('localhost', 'root', 'pw');
mysql_select_db ("db");
$sql = "SELECT material_name FROM materials";
$result = mysql_query($sql);
echo "<td><select name='materials'>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['material_name'] . "'>" .
$row['material_name'] . "</option>";
}
echo "</select></td></tr> ";
$sql2 = "SELECT location_name From locations";
$result2 = mysql_query($sql2);
?>
<td><strong>Locations</strong></td>
<?php
echo "<td><select name='locations'>";
while ($row2 = mysql_fetch_array($result2))
{
echo "<option value='" . $row2['location_name'] . "'>" .
$row2['location_name'] . "</option>";
}
echo "</select></td></tr>";
?>
<tr>
<td><button name="submit" type=submit>Generate</button></td>
</tr>
</table>
</form>
最佳答案
您想从表中获取特定 Material 的记录吗?
如果您使用 -
$result = mysql_query("SELECT " . $material . " FROM materials");
这行看起来不太好..实际上要选择 Material ,您必须有 where 子句,并且在变量 $material 的位置您需要传递您想要选择的列或 * 对于所有列。您的查询可能是这样的 -
$result = mysql_query("SELECT * FROM materials where Material_Name = ".$material);
现在它将返回 Material 表中的所有记录,其中 Material 名称是您传递的值。
关于php - SQL 无法获取记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21330374/