Display One SQLite Record with PHP PDO

Fetch one row by ID

Use a prepared statement and fetch() when you expect one record.

<?php
$stmt = $db->prepare('SELECT id, name, class, mark FROM student WHERE id = :id');
$stmt->execute([':id' => 5]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row) {
    echo htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8');
}
?>

Current example first; detailed examples below are retained for additional learning and comparison.


We will create the database and connection object.
<?php 
// Create (connect to) SQLite database in file
  $my_conn = new PDO('sqlite:my_student.sqlite3');
// Set errormode to exceptions
  $my_conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
 
// Query to collect all columns of a particular record
$query="select * from student where id=3";

if($result=$my_conn->query($query)){
$row = $result->fetch(PDO::FETCH_OBJ);

//print_r($row);

echo "ID = $row->id";
echo "<br>Name = $row->name";
echo "<br>Class = $row->class";
echo "<br>Mark = $row->mark";

}
else{
echo " Not able get data ";
print_r($my_conn->errorInfo()); 
}
$my_conn = null;
?>
In above code we have used student ID to get all columns of the row and displayed the same. We may have to collect the ID value from external source so it is better to use parameter query so we can Binds a parameter to a statement variable.
<?php 
require "menu.php"; 
// Create (connect to) SQLite database in file
   $my_conn = new PDO('sqlite:my_student.sqlite3');
// Set errormode to exceptions
   $my_conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
 
$id=3; // Student id to collect single record
//Query to collect all column of a particular record
$query="select * from student where id=:id"; 
$count = $my_conn->prepare($query);       
$count->bindParam(':id', $id,PDO::PARAM_INT,5);
if($count->execute()){
$row = $count->fetch(PDO::FETCH_OBJ);

//print_r($row);

echo "ID = $row->id";
echo "<br>Name = $row->name";
echo "<br>Class = $row->class";
echo "<br>Mark = $row->mark";

}
else{
echo " Not able get data ";
print_r($my_conn->errorInfo()); 
}
$my_conn = null;
?>
Output is here
ID = 3
Name = Arnold
Class = Three
Mark = 55
Download sample script for SQLite with instructions on how to use.

SQLite Connection Update records

PHP SQLite PDO Functions


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer