L
L
l55uiz2017-03-11 22:40:54
PHP
l55uiz, 2017-03-11 22:40:54

How to count the number of orders?

Can you tell me how to count the number of orders for a user?
The orders table has a user_id field that stores the user ID taken from the session. And you need to display how many orders there were.
This code displays 0 for me

public function countOrders()
  {
    try
    {  
      $stmt = $this->runQuery("SELECT count(user_id) FROM orders GROUP BY user_id WHERE user_id =:user_id");
      $stmt->bindValue(":user_id", $_SESSION['user_session'], PDO::PARAM_STR);
      echo $stmt->rowCount(); 
    }
    catch(PDOException $e)
    {
      echo 'Ошибка.';
    }     
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
ThunderCat, 2017-03-11
@l55uiz

$stmt = $this->runQuery("SELECT count(id) FROM orders WHERE user_id =:user_id");

and then you even overdid
it why? Considering that you are already choosing an account?

F
FanatPHP, 2017-03-13
@FanatPHP

A typical cargo-cult code, in which there is a bunch of meaningless body movements and what is really needed is missing.
What it should actually look like:

public function countOrders($user_id)
{
      $stmt = $this->pdo->prepare("SELECT count(1) FROM orders WHERE user_id =?");
      $stmt->execute([$user_id]);
      return $stmt->fetchColumn(); 
}
// и использование
echo $obj->countOrders($_SESSION['user_session']);

I won’t go into details, but when you understand why you need to write this way, and now you have hell written in both versions, you can consider that you graduated from elementary school in programming.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question