Jump to content

Recommended Posts

Let's say I want to select a record based on what the user put in the form:

 

$lname = mysql_real_escape_string($_POST['lname']);
$mrn_pre = $_POST['mrn'];
$mrn = ereg_replace("[^A-Za-z0-9]", "", $mrn_pre);
$resident = mysql_real_escape_string($_POST['resident']);

include "connectdb";
$query = "SELECT * FROM active consults WHERE patient_name = '$lname' AND mrn='$mrn' AND resident ='$resident'";
$results = mysql_query ($query) or die (mysql_error());

 

But what if the user left some fields blank.  How would I search and ignore the blank fields (otherwise it will search WHERE mrn = " " and no record will get selected).

I could probably do this with a very complicated if else type of thing but was wondering if there is an easier (and more elegant) way to exclude blank POST variables in the query.

Link to comment
https://forums.phpfreaks.com/topic/174037-exclude-a-posted-term-if-it-is-blank/
Share on other sites

$query = "SELECT * FROM active consults WHERE patient_name = '$lname'";
$query .= (!empty(trim($mrn)) ? "AND mrn='$mrn' AND resident ='$resident'" : "AND resident ='$resident'";
$results = mysql_query($query);

 

I added the trim in there so if there were just blanks, IE " " would become "".

 

Hope that helps

Also do I need to put trim in front of each variable?  I saw you just put it in front of mrn.

Addendum: I get this error:

 

Fatal error: Can't use function return value in write context in C:\wamp\www\consults\dosearch.php on line 12

 

line 12 is the one with the trim statement.

 

Thank you.  But what does the ? signify after (trim($mrn))?  Is that a type of if statement?

 

that is called a ternary operator. check out This page on the manual

to find out more. Its basically a mini if statement.

 

its probably a good idea to put a trim in front of each statement so you don't have extra whitespace that might cause problems. but as far as needing it, unless you alway want to check that those are not empty and that they may have whitespace, i suppose there isn't a need for it. however I would suggest trimming those values anyways,

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.