PHP MySQL changing select query based on variables -
i've got 4 variables (year, month, projectcode , type).
so if person submits year , leave other 3 variables blank select query must select * table year(trandate) = $var
if user supplies year & month query must select * table year(trandate) = $var , month(trandate) = $var1
if user selects year, month & projectcode , leave type blank query must select * table year(trandate) = $var , month(trandate) = $var1 , projcode = $var3
and on. how go programming this, otherwhise have awful lot of combinations?
hope question clear.
for example have far can see there combinations:
if (empty($ej1year) && empty($ej1month) && empty($ej1proj) && empty($ej1type)) { $rows = mysql_query("select a.employee ,a.trandate ,concat(a.workdone, '-', wc.briefdescription) workcodeactivity ,concat(a.custname, '-', cl.shortname) clientdet ,a.qty ,a.rate ,a.amount ,a.ref ,a.projcode ,a.type ,a.qty*a.rate costrate transaction left join workcodes wc on a.workdone=wc.workcodeno left join clients cl on a.custname=cl.entityno"); } elseif (empty($ej1year) && !empty($ej1month)) { $rows = mysql_query("select a.employee ,a.trandate ,concat(a.workdone, '-', wc.briefdescription) workcodeactivity ,concat(a.custname, '-', cl.shortname) clientdet ,a.qty ,a.rate ,a.amount ,a.ref ,a.projcode ,a.type ,a.qty*a.rate costrate transaction left join workcodes wc on a.workdone=wc.workcodeno left join clients cl on a.custname=cl.entityno month(trandate) = '$ej1month'"); } elseif
something should work:
<?php $where = array(); $binds = array(); if ($_post['month'] !== '') { $where[] = 'month = ?'; $binds[] = $_post['month']; } if ($_post['year'] !== '') { $where[] = 'year = ?'; $binds[] = $_post['year']; } ... $query = 'select * table ' . implode(' , ', $where); $db->execute($query, $binds);
you'd want add check see if variables set. if don't mind if empty, can change
$where = array();
to
$where = array(1);
which end "where 1" in query, selecting everything.
edit: see using mysql_ functions, that's not ideal they deprecated. should update pdo or mysqli asap. here's version work mysql_
<?php $where = array(); if ($_post['month'] !== '') { $where[] = "month = '" . mysql_real_escape_string($_post['month']) . "'"; } if ($_post['year'] !== '') { $where[] = "year = '" . mysql_real_escape_string($_post['year']) . "'"; } ... $query = 'select * table ' . implode(' , ', $where); $result = mysql_query($query);
Comments
Post a Comment