Devesh Agrawal Devesh Agrawal - 5 months ago 14
PHP Question

How to get single value in php instead of $stmt->fetchObject();

This is my function.

public function getOrderValue($order_id) {
$sql = "select SUM(OD.quantity * OD.product_sell_price) from table_order_details OD where OD.order_id= :order_id AND OD.is_delete = 0";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("order_id", $order_id);
$stmt->execute();
$user = $stmt->fetchObject();
return $user;

} catch(PDOException $e) {
return NULL;
//echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}


As there is only single column in query, How to return that value? Basically i want how to fetch SUM alone instead of returning an object $stmt->fetchObject();

Answer

You can use fetchColumn, but there is nothing wrong with returning $user->total or something similar.

public function getOrderValue($order_id) {
$sql = "SELECT SUM(OD.quantity * OD.product_sell_price) AS total FROM table_order_details OD WHERE OD.order_id= :order_id AND OD.is_delete = 0";
try {
    $stmt = $this->db->prepare($sql);
    $stmt->bindParam("order_id", $order_id);
    $stmt->execute();
    $total = $stmt->fetchColumn();
    return $total;
} catch(PDOException $e) {
    return NULL;
}

}