首页 \ 问答 \ 重叠模式匹配(Overlapping pattern matches)

重叠模式匹配(Overlapping pattern matches)

我有以下代码:

test :: String -> Bool
test "g" = True
test "global" = True
test _ = False

当我把它加载到GHCi(7.0.3)时,我得到:

Warning: Pattern match(es) are overlapped
         In an equation for `test': test "g" = ...

这是一个错误还是我错过了什么?

以下是:

test "" == False
test "g" == True
test "gl" == False
test "global" == True
test "globalx" == False

更新:

我正在使用{-# LANGUAGE OverloadedStrings #-}


I have the following code:

test :: String -> Bool
test "g" = True
test "global" = True
test _ = False

When I load it into GHCi (7.0.3), I get:

Warning: Pattern match(es) are overlapped
         In an equation for `test': test "g" = ...

Is this a bug or am I missing something here?

The following hold:

test "" == False
test "g" == True
test "gl" == False
test "global" == True
test "globalx" == False

UPDATE:

I am using {-# LANGUAGE OverloadedStrings #-}.


原文:https://stackoverflow.com/questions/8993656
更新时间:2023-07-18 12:07

最满意答案

是的,PDO没有用于分隔表名和列名等标识符的内置函数。 PDO::quote()函数仅用于字符串文字和日期文字。

对于它的价值,当我使用Zend Framework时,我实现了一个quoteIdentifier()函数。

你说得对, SELECT *提取所有列,可能会使用更多的内存并破坏覆盖索引的好处。

我的建议是将列名列入白名单 。 也就是说,确保$ info实际命名一table 。 那么你不必担心列名不存在,或者包含一个奇怪的字符或任何东西。 您可以控制要放入查询的合法列。

无论如何,你也应该分隔列名。 如果列名包含标点符号,空格,国际字符或匹配SQL保留字,则分隔标识符是必需的。 请参阅不同的数据库使用不同的名称引号

function getInfoById($id, $info) {
    // you can make this a literal list, or query it from DESC or INFORMATION_SCHEMA
    $cols = array('col1', 'col2', 'col3');

    if (array_search($info, $cols) === false) {
      return false;
    }
    $sql = "SELECT `$info` FROM table WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    if ($stmt === false) {
      return false;
    }
    . . .
}

我在演示文稿SQL注入神话和谬误中展示了更多白名单示例。


Yes, PDO does not have a builtin function for delimiting identifiers like table names and column names. The PDO::quote() function is only for string literals and date literals.

For what it's worth, when I worked on Zend Framework, I implemented a quoteIdentifier() function.

You're right that SELECT * fetches all columns, likely using more memory and spoiling the benefit of covering indexes.

My recommendation is to whitelist column names. That is, make sure $info actually names a column of table. Then you don't need to worry about the column name not existing, or containing a strange character, or anything. You get to control the set of columns that are legitimate to put in the query.

You should also delimit the column name anyway. Delimited identifiers are necessary if the column name contains punctuation, whitespace, international characters, or matches an SQL reserved word. See Do different databases use different name quote?

function getInfoById($id, $info) {
    // you can make this a literal list, or query it from DESC or INFORMATION_SCHEMA
    $cols = array('col1', 'col2', 'col3');

    if (array_search($info, $cols) === false) {
      return false;
    }
    $sql = "SELECT `$info` FROM table WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    if ($stmt === false) {
      return false;
    }
    . . .
}

I show more examples of whitelisting in my presentation SQL Injection Myths and Fallacies.

相关问答

更多
  • 是的,PDO没有用于分隔表名和列名等标识符的内置函数。 PDO::quote()函数仅用于字符串文字和日期文字。 对于它的价值,当我使用Zend Framework时,我实现了一个quoteIdentifier()函数。 你说得对, SELECT *提取所有列,可能会使用更多的内存并破坏覆盖索引的好处。 我的建议是将列名列入白名单 。 也就是说,确保$ info实际命名一table 。 那么你不必担心列名不存在,或者包含一个奇怪的字符或任何东西。 您可以控制要放入查询的合法列。 无论如何,你也应该分隔列名。 ...
  • 你用两个参数调用查询(比如在第一个Query中,在第二个查询中),即使它们具有相同的值..所以你必须传递两个参数 $qResults->execute([$c1, $c1]); You invoke the query with two parameters (like in the first Query and like in the second) even if they have the same value .. so you have to pass two parameters $qRes ...
  • 我相信问题是你的单引号。 尝试这个: $sth = $conn->prepare("SELECT `id`, `short-des`, `full-des`, `image-urls`, `date-created` FROM projects"); 注意:反引号`与单引号' 。 I believe the problem is your single-quotes. Try this: $sth = $conn->prepare("SELECT `id`, `short-des`, `full-des` ...
  • 你需要做这样的事情: $column = 'someColumn'; $stmt = $db->prepare("UPDATE tableName SET {$column} = :columnValue WHERE ID = :recordId"); 参数化占位符仅用于值。 我建议你阅读你的问题上发表的评论@YourCommonSense。 You would need to do something like this: $column = 'someColumn'; $stmt = $db->p ...
  • 尝试这个: # Took out ID, as it should be auto_increment and handled by database $statement = $db->prepare("INSERT INTO Table (Column1, Column2) VALUES (:col1, :col2)"); $statement->bindValue(':col1', $var1, PDO::PARAM_STR); $statement->bindValue(':col2', $var ...
  • 我使用下面的代码: // In case an error occured during statement execution, throw an exception if (!$stmt->execute()) { // Error handling with $stmt->errorInfo() } // Fetch all results $data = $stmt->fetchAll(PDO::FETCH_ASSOC); 之后不需要foreach循环来处理数据。 I use the f ...
  • 只有在参数化准备好的语句的情况下,它才有助于单引号,否则你所做的只是字符串连接,并且必须适当地形成你的SQL。 试试像这样: $sql = "INSERT INTO anagrafiche SET id_ndg = :protocol, nick = :nick, nome = :nome, ... "; $params = array( ':protocol' => $protocol, ':nick' => ...
  • 问题是由于数据库记录中带有重音的字母。 解决方案是使用array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4")将连接的字符集设置为“UTF-8 MultiByte 4”,如下所示: try { $this->conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD, array(PDO::MYSQL_ATTR_I ...
  • 您可以通过询问数据库哪些列对给定数据库表有效来使用动态白名单。 这是一个额外的SQL查询,但安全性很好。 select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA = :databaseName and TABLE_NAME = :tableName 获取结果,然后确保所有动态列名都在结果集中。 我相信视图包含在INFORMATION_SCHEMA.COLUMNS ,因此它应该只是简单的工作。 然后在组装动态sql时 ...
  • 诸如columnNames和tableNames之类的标识符不应该用单引号括起来,而应该用反引号包装。 使用单引号进行换行会将标识符转换为字符串文字。 INSERT INTO myTbl.uploads(id, name, `group`) VALUES (:id,:user,:group) 何时使用单引号,双引号和反引号? Identifiers such as columnNames and tableNames shouldn't be wrap with single quotes, but in ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)