使用 PREPARE 命令(SQL) 与 PDO 或 mysqli 函数
我使用 PHP 开发 Web 应用程序并使用 MySQL 作为数据库。我正在尝试了解准备好的语句的用法,并且只是迈出第一步。
据我了解,预备语句主要是为了:
提高查询效率(预解析、缓存执行计划、客户端和服务器之间
确保免受代码注入攻击(对此并不完全清楚,但我想我有基本的了解)
(可能还有其他用途)
问题是,
为什么不直接使用 MySQL 提供的 PREPARE 语句并预先准备好语句,然后使用这些语句在你的 PHP 应用程序中,是 PDO 还是 mysqli?更好的是,使用这些准备好的语句创建存储过程并仅将这些语句公开给 PHP 程序员?
这样,进行正确查询的实际负担就由数据库程序员分离/处理。 PHP程序员可以完全只专注于应用程序的实现和优化。
我预计我很快就会使用的数据库不会发生任何变化。 MySQL 满足所有要求。但为了保持我的应用程序干净且与数据库无关,我可以使用 PDO。或者坚持程序编码并执行 mysqli
这是构建应用程序的有效/经过尝试和测试的方法吗?
谢谢
I develop web applications using PHP and use MySQL as the database. I am trying to understand the usage of prepared statements and am just taking my first steps.
As I understand it, prepared statements are primarily to:
Increase the efficiency of the query(pre-parsing, cached execution plan, binary data transfer between client and server)
Ensure protection from code injection attacks (not entirely clear on this, but I think I have a basic understanding)
(may be there are other uses as well)
The question is,
why not just use the PREPARE statement that MySQL provides and make your prepared statements before hand and then use those in your PHP application, either PDO or mysqli? Better yet, make stored procedures using these prepared statements and expose only those to the PHP programmers?
This way, the actual burden of making the correct queries is separated / handled by the database programmer. PHP programmer can completely focus only on the application implementation and optimization.
I don't foresee any changes in the database that I would be using anytime soon. MySQL meets all the requirements. But just to keep my application clean and DB agnostic, I could use PDO. Or stick to procedural coding and do mysqli
Is this a valid / tried and tested approach to go about building an application?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PREPARE 语句的结果有些特殊,不能返回给用户。当然,您可以通过存储在 MySQL 中的变量中来使用它。但是,这不是标准的。 MySQL 为您提供 API,以便 PDO 驱动程序利用它们,并且您可以编写与数据库无关的代码。我认为完全没有理由不这样做。在使用 PDO 的众多功能中,我特别喜欢 DBTNG(Drupal 7 DB 层剥离),因为我有一部分编写它:)和idiorm。
The result of the PREPARE statement is somewhat special and is not returnable to the user. You can use it by storing in a variable of course in MySQL. But, that's not standard. MySQL gives you APIs so that the PDO driver utilizes them and you can write DB agnostic code. I see totally no reason not to do that. Among the many things using PDO I particularly like DBTNG (Drupal 7 DB layer spinned off) because I had a part in writing it :) and idiorm.