Dreamscapist Dreamscapist - 3 months ago 9
MySQL Question

PHP create MySQL query with conditions if/elseif/else

I'm new to PHP & MySQL and was trying to use php to create query for MySQL below is the current state of the code and it's still WIP but the if/elseif structure already gives the desired output which varies according to data input, which for example could be as follows

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


I've confirmed that the query line itself works in MySQL but I would need to somehow get it inside the MySQL_query($con, The query here).

So how do I get the php output of whole if/elseif query line build in variable or similar to be used?

<?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");
?>

Answer

Check this example and try to modify your code,

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

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