如果/ elseif / else,PHP使用条件创建MySQL查询

时间:2014-09-24 11:46:09

标签: php mysql sql if-statement

我是PHP&amp;的新手MySQL并试图使用php为MySQL创建查询,下面是代码的当前状态,它仍然是WIP但是if / elseif结构已经提供了根据数据输入而变化的所需输出,例如可以如下所示< / p>

"SELECT * FROM tuntikortti WHERE PVM BETWEEN '2014-09-11' AND '2014-09-27' AND Henkilo =
 'Van' AND Tyonumero = '123456' AND Toiminto = '123';"

我已经确认查询行本身可以在MySQL中运行,但我需要以某种方式将其放入MySQL_query($ con,此处的查询)。

那么如何获得整个if / elseif查询行构建的变量或类似的php输出?

<?php
include("db_connect.php");

$pvm1       = $_POST['pvm1'];
$pvm2       = $_POST['pvm2'];
$henkilo    = $_POST['henkilo'];
$tyonumero  = $_POST['tyonumero'];
$toiminto   = $_POST['toiminto'];

/* MySQL query line build, beginning */
ECHO "SELECT * FROM tuntikortti WHERE ";

    /* PVM */
    if(!empty($pvm1) && !empty($pvm2)){
        echo "PVM BETWEEN '". $pvm1 ."' AND '". $pvm2 ."'";
    } elseif(!empty($pvm1)) {
        echo "PVM = '". $pvm1 ."'";
    };

    /* Henkilo */
    if(!empty($henkilo) && !empty($pvm1)){
        echo " AND Henkilo = '". $henkilo ."'";
    } elseif(!empty($henkilo)) {
        echo " Henkilo = '". $henkilo ."'";
    };

    /* Tyonumero */
    if(!empty($tyonumero) && (!empty($pvm1) || !empty($henkilo))){
            echo " AND Tyonumero = '". $tyonumero ."'";
        } elseif(!empty($tyonumero)) {
            echo " Tyonumero = '". $tyonumero ."'";
        };

    /* Toiminto */
    if(!empty($toiminto) && (!empty($tyonumero) || !empty($pvm1) || !empty($henkilo))){
        echo "  AND Toiminto = '". $toiminto ."'";
    } elseif(!empty($toiminto)) {
            echo " Toiminto = '". $toiminto ."'";
        };

    echo ";";

    $query = mysqli_query($sql,$con);

echo "<table border='1'>
<tr>
<th>TID</th>
<th>PVM</th>
<th>Henkilo</th>
<th>Työnumero</th>
<th>Toiminto</th>
<th>Tunnit</th>
<th>Selite</th>
</tr>";

while($row = mysqli_fetch_array($query)) {
  echo "<tr>";
  echo "<td>" . $row['TID'] . "</td>";
  echo "<td>" . $row['PVM'] . "</td>";
  echo "<td>" . $row['Henkilo'] . "</td>";
  echo "<td>" . $row['Tyonumero'] . "</td>";
  echo "<td>" . $row['Toiminto'] . "</td>";
  echo "<td>" . $row['Tunnit'] . "</td>";
  echo "<td class='selitetyyli'>" . $row['Selite'] . "</td>";
  echo "</tr>";
}

echo "</table>";

include("db_close_connection.php");
    ?>

1 个答案:

答案 0 :(得分:3)

检查此示例并尝试修改代码,

$sql = '';
$sql = "SELECT * FROM tablename WHERE ";
if(condition){
    $sql.= "fieldname = 'value'";
} elseif(condition) {
    $sql.= "fieldname = 'value'";
};

$sql.= ";";
$query = mysqli_query($con,$sql);