如何正确使用 PDO 对象进行参数化 SELECT 查询
我尝试按照 PHP.net 说明进行 SELECT
查询,但我不确定执行此操作的最佳方法。
如果可能的话,我想使用参数化的 SELECT 查询来返回表中 name
字段与参数匹配的 ID
。 这应该返回一个ID
,因为它是唯一的。
然后,我想使用该 ID 将 INSERT
插入到另一个表中,因此我需要确定它是否成功。
我还读到您可以准备查询以供重用,但我不确定这有什么帮助。
I've tried following the PHP.net instructions for doing SELECT
queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT
query, if possible, to return the ID
in a table where the name
field matches the parameter. This should return one ID
because it will be unique.
I would then like to use that ID
for an INSERT
into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
方法一:使用PDO查询方法
获取行数
方法二:带参数的语句
参数
方法三:绑定 要了解更多信息,请查看此链接
Method 1:USE PDO query method
Getting Row Count
Method 2: Statements With Parameters
Method 3:Bind parameters
Want to know more look at this link
如果您在单页中使用内联编码并且不使用 oops,而不是使用这个完整的示例,它肯定会有所帮助
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
您可以像这样选择数据:
您以相同的方式插入:
我建议您将 PDO 配置为在出错时抛出异常。 如果任何查询失败,您将收到
PDOException
- 无需显式检查。 要打开异常,请在创建$db
对象后调用此函数:You select data like this:
You insert in the same way:
I recommend that you configure PDO to throw exceptions upon error. You would then get a
PDOException
if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the$db
object:我最近一直在使用 PDO,上面的答案是完全正确的,但我只是想证明以下内容也有效。
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
您可以使用
bindParam
或bindValue
方法来帮助准备语句。它使事情第一眼看上去更加清晰,而不是执行
$check->execute(array(':name' => $name));
特别是当您绑定多个值/变量时。检查下面清晰易读的示例:
如果您期望多行,请删除
LIMIT 1
并将获取方法更改为fetchAll
:You can use the
bindParam
orbindValue
methods to help prepare your statement.It makes things more clear on first sight instead of doing
$check->execute(array(':name' => $name));
Especially if you are binding multiple values/variables.Check the clear, easy to read example below:
If you are expecting multiple rows remove the
LIMIT 1
and change the fetch method intofetchAll
:这里有一个完整的答案,可供使用:
这里
$dbh
是 PDO 数据库连接器,并且基于表users
中的id
我们已经使用fetch();
获取了用户名
,我希望这对某人有帮助,祝您愉快!
A litle bit complete answer is here with all ready for use:
Here
$dbh
is PDO db connecter, and based onid
from tableusers
we've get theusername
usingfetch();
I hope this help someone, Enjoy!