如果查询中没有占位符/动态数据,您可以省略PDO准备吗? [英] Can you omit PDO prepare if there's no placeholder/dynamic data in a query?

查看:110
本文介绍了如果查询中没有占位符/动态数据,您可以省略PDO准备吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在使用将PDO与MySQL数据库配合使用的应用程序.

I'm working on an application at the moment that uses PDO with a MySQL database.

我看到了一些查询,这些查询只是非常简单的SELECT语句,例如

I'm seeing some queries, which are just very simple SELECT statements, e.g.

SELECT * FROM table ORDER BY name ASC

该代码不使用prepare,例如:

    $sql = "SELECT * FROM " . $this->table . " ORDER BY name ASC";
    $stmt = $this->db->query($sql);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $results;

如果查询中没有占位符,是否可以执行此操作(即不使用prepare)?

Is it ok to do this, i.e. without using prepare, if there's no placeholders in the query?

我问这个问题的原因是因为根据文档,它说

The reason I've asked this is because according to the documentation it says

SQL语句可以包含或更多个命名(:name)或问号(?)参数标记

The SQL statement can contain zero or more named (:name) or question mark (?) parameter markers

这让我想知道为什么在没有()个参数标记的情况下为什么要使用它?

which makes me wonder why you'd use this in the case of having no (zero) parameter markers?

推荐答案

是的,因为使用准备好的语句有两个主要原因:

Yes, because the use of prepared statements have 2 main causes:

  1. 增强使用不同参数运行相同的查询.
  2. 通过从参数中分离sql代码来防止sql注入.

由于没有准备好的语句可以处理的参数(表名不能是参数),因此将查询作为准备好的语句进行推送不会获得任何好处.

Since you have no parameters that could be handled by a prepared statement (table names cannot be a parameter), you do not gain anything by pushing the query through as a prepared statement.

您仍然需要确保$this->table返回的任何内容都不会对生成的sql代码造成任何问题.

You still need to make sure that whatever is returned by $this->table will not cause any issues with the generated sql code.

这篇关于如果查询中没有占位符/动态数据,您可以省略PDO准备吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆