0

I want to count the value of column in MySQL and show the result in my page using PHP.

I tried this to get the column value

$smt=$conn->prepare("SELECT SUM(Admin_Status) FROM aplic");
$smt->execute();
$result=$smt->fetch(PDO::FETCH_OBJ);
$res=$result->SUM(Admin_Status);
echo $res;

To be more specific, I'm making a PM (personal messaging system) and for that I created the read and unread column in the table, now I want that user see how many new messages (s)he has.

1
  • Give your sum an alias -> "SELECT SUM(Admin_Status) as AdminStatusSum FROM aplic" which you can then access -> $result->AdminStatusSum; Commented Aug 8, 2014 at 5:20

1 Answer 1

1

You cannot use the return value of the query that way because PHP will interpret it as a method to execute.

If you give the field you retrieve an alias in the query, you'll be able to use it correctly from the object.

SELECT SUM(Admin_Status) AS status FROM aplic

Will allow you to use

$result=$smt->fetch(PDO::FETCH_OBJ);
$res=$result->status;
echo $res;

Alternatively, you might be able to use the following syntax

$res=$result->{'SUM(Admin_Status)'}

But I'd very much vote on using the first alternative and just giving the returned column an alias.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.