0

Hello,

I am look for some help with a query where the query changes on the basis of input parameters.

Like

$variable = 'abc';
$rs=mysql_query("SELECT * FROM table WHERE `column`='$variable'");

But what about a scenario where this variable is not assigned or is null or blank. In that case I'd like the query to ignore that column altogether and look into other parameters.

I have been looking into it for a while but haven't found anything useful. I am not even sure if its possible. Any help or inputs will be appreciated!

Thanks

Edited by sarovarc: Spelling!

2
Contributors
1
Reply
15
Views
4 Years
Discussion Span
Last Post by bops
1

It's just a matter of programming your issue into the script. Build the query dynamically by checking variables and deciding whether or not to include them in your query. For example:

<?php
    $var = "abc";

    $query = "SELECT * FROM `table`";
    $queryWhere = array();
    // Make sure $var is set and is not empty
    if (!empty($var)) {
        $queryWhere[] = "`column` = '$var'";
    }

    // Do the same for other variables.

    if (count($queryWhere) > 0) {
        $query .= " WHERE " . implode(" AND ", $queryWhere) . ";";
    }
    else {
        // Nothing to put in WHERE
    }
?>

Remember to escape anything that a user has the ability to enter using mysql_real_escape_string()

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.