SQL无法获取记录

时间:2014-01-24 10:33:57

标签: php mysql sql csv

我正在尝试根据用户的需求将特定记录输出到.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>

1 个答案:

答案 0 :(得分:2)

你想从表中获取特定材料的记录吗?

如果您使用 -

 $result = mysql_query("SELECT " . $material . " FROM materials");

这一行看起来不太好..实际上选择必须具有where子句的材料,并且在变量$ material的位置,你需要传递你要为所有列选择或*的列。您的查询可能是这样的 -

 $result = mysql_query("SELECT * FROM materials where Material_Name = ".$material); 

现在它将返回材料表中所有记录,其中材料名称是您传递的值。