简体   繁体   English

Select 在 MYSQL — Select 所有记录

[英]Select in MYSQL — Select all the records

I have a function like below:我有一个 function 如下所示:

public function select($id=null) {
    $query = "select * from press_releases where id = {$id}";

    $results = $this->db->query($query);

    return $results;
}

If no $id is specified during function invoke, I want to return all the records but I think NULL default value is not a good option for that.如果在 function 调用期间未指定$id ,我想返回所有记录,但我认为NULL默认值不是一个好的选择。 What should I do instead of NULL to retrieve all the records other than using a another query which doesn't specify the id field in the where section.除了使用未在 where 部分中指定 id 字段的另一个查询之外,我应该怎么做而不是NULL来检索所有记录。

Thanks...谢谢...

$query = "select * from press_releases";
if (!empty($id))
{
   $query .= "where id = {$id}";
}

If $id is an integer, I would use:如果$id是 integer,我会使用:

$id = (int) $id;
if ($id > 0)
...

Either way I would make sure $id is safe to use.无论哪种方式,我都会确保$id可以安全使用。

This may work:这可能有效:

$query = "select * from press_releases where id = {$id} OR {$id} IS NULL";

You could replace the where operator to LIKE, as in您可以将 where 运算符替换为 LIKE,如

$query = "select * from press_releases where id LIKE '{$id}'";

and change the default value to the '%', but I don't like this solution for efficiency reasons.并将默认值更改为“%”,但出于效率原因,我不喜欢这种解决方案。

You should do that only if you absolutely need to keep the query as you written.仅当您绝对需要按您所写的方式保留查询时,您才应该这样做。 Otherwise change the query to append the where condition only if the $id parameter is given.否则将查询更改为 append where 条件,仅当给出$id参数时。 That would be the right solution.那将是正确的解决方案。

SELECT DISTINCT id FROM press_releases SELECT DISTINCT id FROM press_releases

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

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