如何正确使用 PDO 对象进行参数化 SELECT 查询 [英] How can I properly use a PDO object for a parameterized SELECT query
问题描述
我已尝试按照 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
查询返回 ID
表中 name
字段与范围.这应该返回一个 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.
推荐答案
您可以像这样选择数据:
You select data like this:
$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屋!