sql - Building interactive WHERE clause for Postgresql queries from PHP -
i'm using postgresql 9.2 , php 5.5 on linux. have database "patient" records in it, , i'm displaying records on web page. works fine, need add interactive filters display types of records depending on filters user engages, having 10 checkboxes build ad-hoc clause based off of information , rerun query in realtime. i'm bit unclear how that.
how 1 approach using php?
all need recieve data of user's selected filters $_post or $_get , make small function loop concatenate way query needs it.
something this... in case have 1 field in db match with. it's simple scenario , more fields you'll need make add field need in each case, nothing complex.
<?php //recieve filters , save them in array $keys[] = isset($_post['filter1'])?'$_post['filter1']':''; //this sends empty if filter not set. $keys[] = isset($_post['filter2'])?'$_post['filter2']':''; $keys[] = isset($_post['filter3'])?'$_post['filter3']':''; //go through array , concatenate string need. of course, might need , instead of or, depending on needs are. foreach ($keys $id => $value) { if($id > 0){ $filters.=" or "; } $filters.=" your_field = '".$value."' "; } //at point $filters has string //then make connection , send query. notice how select concatenates $filters variable $host = "localhost"; $user = "user"; $pass = "pass"; $db = "database"; $con = pg_connect("host=$host dbname=$db user=$user password=$pass") or die ("could not connect server\n"); $query = "select * table ".$filters; $rs = pg_query($con, $query) or die("cannot execute query: $query\n"); while ($row = pg_fetch_row($rs)) { echo "$row[0] $row[1] $row[2]\n"; //or whatever way want print it... } pg_close($con); ?>
the above code variables form sent 3 variables (assuming of them correspond same field in db, , makes string use clause.
if have more 1 field of db filter through, need careful on how match user input fields.
note: did not add here practical reasons... please, please sanitize user input.. sanitize user input before using user controlled data in queries.
good luck.
Comments
Post a Comment