如何正确使用PDO对象进行参数化SELECT查询 [英] How can I properly use a PDO object for a parameterized SELECT query

查看:55
本文介绍了如何正确使用PDO对象进行参数化SELECT查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试按照PHP.net的说明进行SELECT查询,但是我不确定执行此操作的最佳方法.

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.

我想使用参数化的SELECT查询,如果可能的话,在name字段与参数匹配的表中返回ID.这应该返回一个ID,因为它将是唯一的.

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.

然后我想将该ID用于INSERT到另一个表中,所以我将需要确定它是否成功.

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.

推荐答案

您选择像这样的数据:

$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator

您以相同的方式插入:

$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));

我建议您将PDO配置为在出错时引发异常.如果任何查询失败,您将得到一个PDOException-无需显式检查.要打开异常,请在创建$db对象后立即调用此方法:

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:

$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

这篇关于如何正确使用PDO对象进行参数化SELECT查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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