Home Ask Login Register

Developers Planet

Your answer is one click away!

user5603796 February 2016

Simplest method to retrieve single (and only) row in SQLite using PDO

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.


Don't Panic February 2016

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.

Post Status

Asked in February 2016
Viewed 2,974 times
Voted 11
Answered 1 times


Leave an answer

Quote of the day: live life