php如果陈述大于0,则陈述采用最低数字

时间:2018-08-27 23:48:38

标签: php mysql

底部是我的代码。 我有8列的数据库 SKU,价格1,价格2,价格3,最低价格,数量1,数量2,数量3

我想在脚本中添加一些if语句,以检查三个参数。 如果qty> 0

目前,我正在从Price1-3导出最低数量的商品,但它没有检查数量是否大于0。

这是我的代码:

<?php 
if (isset($_SERVER['REMOTE_ADDR'])) {
    die(':)');
}

echo "Cron is running";

$hostname   = 'localhost';
$username   = 'user';
$password   = 'pass';
$myDatabase = 'database';
/**
 * Defines the name of the table where data is to be inserted
 */
$table = 'mytable';

try {
    $conn = new PDO('mysql:host=localhost;dbname='.$myDatabase, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    

    $stmt = $conn->prepare("SELECT mytable.SKU AS SKU,  LEAST(price, price2, price3) AS 'Lowest2'
    FROM mytable
    ");


    $stmt->execute();

    $filelocation = 'assets/exports/';
    $filename     = 'export-'.date('Y-m-d H.i.s').'.csv';
    $file_export  =  $filelocation . $filename;

    $data = fopen($file_export, 'w');

    $csv_fields = array();

    $csv_fields[] = 'SKU';
    $csv_fields[] = 'Lowest2';


    fputcsv($data, $csv_fields);

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($data, $row);
    }

} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

1 个答案:

答案 0 :(得分:1)

您可以将查询更改为:

SELECT mytable.SKU AS SKU, 
     LEAST(CASE WHEN qty  > 0 THEN price  ELSE 99999999999 END, 
           CASE WHEN qty2 > 0 THEN price2 ELSE 99999999999 END, 
           CASE WHEN qty3 > 0 THEN price3 ELSE 99999999999 END) AS 'Lowest2'
FROM mytable

我假设所有价格均低于99999999999 ...