PHP: SQL value as filename

2019-07-24 12:24发布

I have this code:

    <?php
    $servername = "Jarvis";
    $username = "TonyStark";
    $password = "iLoveIronMan";
    $dbname = "StarkCompany";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT o.order_id, o.customer_id, op.quantity, op.model FROM oc_order o INNER JOIN oc_order_product op ON o.order_id = op.order_id INNER JOIN oc_product p ON op.product_id = p.product_id WHERE o.order_status_id = 2 AND p.location = 1 ORDER BY o.order_id, op.model";

    $file = fopen('../files/in/filename.csv', 'w');

    if ($rows = mysqli_query($conn, $sql))
    {

        while ($row = mysqli_fetch_assoc($rows))
        {
            fputcsv($file, $row, ';');
        }

        mysqli_free_result($rows);
    }

    mysqli_close($conn);

    fclose($file);
    ?>

Now: How can i take for example the SQL value of the table o.order_id and use this value for my filename? The filename should be example(o.order_id).csv. Is this possible?

1条回答
贼婆χ
2楼-- · 2019-07-24 12:58

You can make your life easier by naming the value like this:

   $sql = "SELECT o.order_id as filename, o.customer_id, op.quantity, op.model FROM oc_order o INNER JOIN oc_order_product op ON o.order_id = op.order_id INNER JOIN oc_product p ON op.product_id = p.product_id WHERE o.order_status_id = 2 AND p.location = 1 ORDER BY o.order_id, op.model";

then when you handle the rows you can use

$rows['filename']
查看更多
登录 后发表回答