简体   繁体   中英

MySQLi optional WHERE clause depending on if condition

While trying to optimize some code I came across another question.. Using usergroups and permissions, I sometimes need to add a WHERE clause when a user has limited permissions.. I could put the whole query inside the if {...} , but that would mean to repeat the same code except one line.. So I changed the code that only the statement is built depending on the if condition, instead of repeating the whole part (statement, prepare, execute, fetch..):

if (in_array('Edit own', $_SESSION['user_r']))
{
    $sql = 'SELECT
                `news_id`
            FROM
                `news`
            WHERE
                `news_user_id` = "' .$_SESSION['user_id']. '"';
}
else if (in_array('Edit all', $_SESSION['user_r']))
{
    $sql = 'SELECT
                `news_id`
            FROM
                `news`';
}

I know it's also possible to "split" the statement, using the if condition within the statement like this :

$sql = 'SELECT
            `news_id`
        FROM
            `news`';

if (in_array('Edit own', $_SESSION['user_r']))
{
     $sql .= ' WHERE
                 `news_user_id` = "' .$_SESSION['user_id']. '"';
}

At first glance the 2. example could be "better" since there is no repeat and the code is short, but when it comes to prepared statements and bind_param(), the first example might be better, because I can add

$stmt = $db->prepare($sql);
$stmt->bind_param('ss', $what, $ever);

directly after the statement inside the if {...} ... and somehow it seems more secure to me...

So which solution should I prefer?

Since there is no other answer, I want to share my "solution":

if (in_array('Edit own', $_SESSION['user_r']))
{
    $sql = 'SELECT
                `news_id`
            FROM
                `news`
            WHERE
                `news_user_id` = ?';

    $stmt = $db->prepare($sql);
    $stmt->bind_param('i', $_SESSION['user_id']);

}
else if (in_array('Edit all', $_SESSION['user_r']))
{
    $sql = 'SELECT
                `news_id`
            FROM
                `news`';

    $stmt = $db->prepare($sql);
}

$stmt->execute();
$stmt->bind_result($news_id);
...

As already mentioned in my question, I'm using the if statement to build the whole statement now. That way, I can use bind_param inside the if statement (if needed), but don't need to repeat the execute/fetch part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM