How do I conditionally add a clause to my query in PHP? -


in search form have, value male, value female, , value both. if select both, not wish have @ "sex = '$sex'"

should this:

if(empty($sex)){ // value empty if chose "both" $query = "select firstname, lastname, id, user_name, sex, last_access, bostadsort users (firstname '%$firstname%' or lastname '%$lastname%')"; }else{ $query = "select firstname, lastname, id, user_name, sex, last_access, bostadsort users (firstname '%$firstname%' or lastname '%$lastname%') , sex = '$sex'"; } 

or there smart way write this?

do never build sql string user input. that's prepared statements for. secure, perform faster when re-executed , they're easy use, use them:

$sql = "   select     firstname, lastname, id, user_name, sex, last_access, bostadsort       users        (firstname '%'|| ? || '%' or lastname '%'|| ? || '%')     , sex = case ? when 'both' sex else ? end "; $stmt = $mysqli->prepare($sql); $stmt->bind_param('ssss', $firstname, $lastname, $sex, $sex);  $result = $stmt->execute(); 

Comments

Popular posts from this blog

unicode - Are email addresses allowed to contain non-alphanumeric characters? -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

c++ - Convert big endian to little endian when reading from a binary file -