使用PDO在SQLite中检索单行(和唯一行)的最简单方法 [英] Simplest method to retrieve single (and only) row in SQLite using PDO
问题描述
我有这个PDO
$stmt = $db->prepare('SELECT * FROM channels WHERE id=:id');
$stmt->bindValue(':id', $id, SQLITE3_INTEGER);
$result = $stmt->execute();
现在什么是访问使用$row['column_name']
返回的行的最简单方法?
我知道可以肯定的是,查询将只返回单行,因为不可能有多个具有相同id
的行,因此我希望保持代码尽可能简单以访问该行. /p>
我在网上看到的示例很长很复杂,使用while循环遍历行等.
它应该像
一样简单$row = $stmt->fetch(PDO::FETCH_ASSOC);
您看到的示例可能更像
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ...
因为它们被设计为处理具有多行的查询结果.但是,如果您知道只有一行,那么就可以放弃循环.当然,这是假设您的查询实际成功执行并返回结果.至少检查一下是个好主意
if ($row) { ...
,然后再尝试在后续代码中使用它.
I have this PDO
$stmt = $db->prepare('SELECT * FROM channels WHERE id=:id');
$stmt->bindValue(':id', $id, SQLITE3_INTEGER);
$result = $stmt->execute();
What now is the simplest method to access the row returned using $row['column_name']
?
I know that for sure the query will only ever return a single row as it's impossible to have more than 1 row with the same id
so I am looking to keep the code as simple as possible to access that row.
Examples I've seen online are quite long and complex, using while loops to loop through rows etc. that I don't need.
It should be as simple as
$row = $stmt->fetch(PDO::FETCH_ASSOC);
The examples you've seen probably have something more like
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ...
because they're designed to process a query result with multiple rows. But if you know you'll only ever have one row, you can just forgo the loop. Of course, this is assuming your query actually executed successfully and returned a result. It would be a good idea to at least check
if ($row) { ...
before you try to use it in your subsequent code.
这篇关于使用PDO在SQLite中检索单行(和唯一行)的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!