PHP REST API CRUD – Step 7
Step 7 Read Data
- After successfully insertion of user, now we read the complete data or single user data. For this we will add 2 functions in user.php of object folder.
// Read Data
public function read()
{
//query to read all data
$query = "select * from " . $this->table;
try {
// Prepare query
$stmt = $this->conn->prepare($query);
// Execute query
$stmt->execute();
return $stmt;
} catch (PDOException $exception) {
echo json_encode(array("Student Read Data Error" => $exception->getMessage()));die;
}
}
//Read Single Student Data
public function readSingleUser($id)
{
//query to read single student data
$query = "select * from " . $this->table . " where id=" . $id;
try {
// Prepare query
$stmt = $this->conn->prepare($query);
// Execute query
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0) {
return $stmt;
} else {
return false;
}
} catch (PDOException $exception) {
echo json_encode(array("Single Student Read Data Error" => $exception->getMessage()));die;
}
}