简体   繁体   English

MySQLi 可选 WHERE 子句取决于 if 条件

[英]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..):在尝试优化一些代码时,我遇到了另一个问题。使用用户组和权限,当用户权限有限时,我有时需要添加WHERE子句。我可以将整个查询放在if {...}中,但是这意味着除了一行之外重复相同的代码。所以我更改了代码,仅根据 if 条件构建语句,而不是重复整个部分(语句、准备、执行、获取..):

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 :我知道也可以使用语句中的 if 条件来“拆分”语句,如下所示:

$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乍一看,2. 示例可能“更好”,因为没有重复并且代码很短,但是当涉及到准备好的语句和 bind_param() 时,第一个示例可能会更好,因为我可以添加

$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...直接在if {...}内的语句之后......不知何故它对我来说似乎更安全......

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.正如我的问题中已经提到的,我现在使用 if 语句来构建整个语句。 That way, I can use bind_param inside the if statement (if needed), but don't need to repeat the execute/fetch part.这样,我可以在 if 语句中使用 bind_param(如果需要),但不需要重复执行/获取部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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