在没有引用的情况下使用 PHP MySQLi 准备语句? [英] Use PHP MySQLi prepared statements without references?

查看:31
本文介绍了在没有引用的情况下使用 PHP MySQLi 准备语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在不传递引用的情况下使用 MySQLi 准备好的语句?

Is there a way to use MySQLi prepared statements without passing references?

[背景:我对 PHP 和 MySQL 非常陌生,但我继承了一个私人的 WordPress 插件来维护,所以我正在学习.]

[Background: I'm extremely new to PHP and to MySQL but I inherited a private WordPress plugin to maintain and so I'm learning both as I go.]

我了解准备好的语句对于防止 SQL 注入很有用,也可能用于加速查询(如果保留语句)但对引用变量的需求似乎很奇怪.是一种称为 bind_param 的想法 预先,然后在进行后续查询时只是将数据设置到那些绑定变量中,而不是与语句进行交互?

I understand that prepared statements are useful for preventing SQL injections and potentially also for speeding up queries (if the statements are kept around) but the need for referenced variables seems odd. Is the idea that one calls bind_param up front and then when making subsequent queries just sets data into those bound variables rather than interacting with the statement at all?

现在我正在重构的代码有 17 个变量,它们传递给 bind_param.我创建了一个包含所有数据的类,因此我不再需要在函数之间传递 17 个变量,但以下显然失败了,因为我的类没有返回引用:

Right now the code I'm refactoring has 17 variables that it passes into bind_param. I made a class to contain all of the data so I don't need to pass 17 variables from function to function anymore but the below obviously fails because my class isn't returning references:

$stmt->bind_param('ssssssisssssssssi',
      $my_class->get(FIELD_ONE),
      $my_class->get(FIELD_TWO),
      /*...x15 more...*/)

鉴于代码当前在 $stmt->execute() 之后立即丢弃 $stmt(因此没有要跟踪的长期变量),有什么方法可以让我使用准备好的语句而不必费心创建临时变量,这样我就可以绑定它们吗?是否有我可以或应该使用的替代类/接口?

Given that the code is currently discarding $stmt immediately after $stmt->execute() (so there aren't long-term variables to track), is there any way for me to use prepared statements without bothering to create temporary variables just so I can bind them? Is there an alternative class/interface I could or should be using?

谢谢!

推荐答案

是的,有.

前一段时间,PHP 中添加了一项非常宝贵的功能 - 参数解包运算符.它有十亿种用途,在这种情况下可以帮助您.

Some time ago an invaluable feature has been added to PHP - an argument unpacking operator. It has a billion uses, and helping you in this situation is among them.

只需在您的值列表之前添加 ...[] 之后 - 瞧,它起作用了!

Just add ...[ before your list of values and ] after - and voila, it works!

$stmt->bind_param('ssssssisssssssssi', ...[
  $my_class->get(FIELD_ONE),
  $my_class->get(FIELD_TWO),
  /*...x15 more...*/
  ]);

提示:这个有用的操作符也可以用于将无聊的准备/绑定/执行过程封装在一个简单的功能.

A hint: this useful operator could be also used to encapsulate that boring prepare/bind/execute process in a simple function.

这篇关于在没有引用的情况下使用 PHP MySQLi 准备语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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