Count lines and echo result

I am trying to do a line count, I want to count a line (nummer) and if there is more than 1 line with the same number then echo. but no matter how many rows I have in my column it only returns 0

      $nummer = $_GET['nummer'];       

      $pdo = Database::connect();
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);    

      $result = $pdo->prepare("select count(*) from rum where nummer=:n");
      $result->bindParam(':n', $nummer, PDO::PARAM_INT);
      $result->execute();

      $rows = $result->fetchAll;
    if(count($rows) >1) {
    echo "1";}
    else {
    echo "0";
      } 

      

+3


source to share


4 answers


It looks like you have two errors.

First, if you ask COUNT(*)

, you get multiple lines. For example: you return to a field named COUNT(*)

with one line containing the number of lines found.

If you replace

$result = $pdo->prepare("select count(*) from rum where nummer=:n");

      

from

$result = $pdo->prepare("select * from rum where nummer=:n");

      



Second: Replace

$rows = $result->fetchAll;

      

FROM

$rows = $result->fetchAll();

      

fetchAll()

is not a property, but a method.

Another way would be your query, but name the field ( MySQL AS

keyword
) and call $rows = $result->fetch();

after that and check the $rows->fieldName

number of rows found.

0


source


The following statement

$result = $pdo->prepare("select count(*) from rum where nummer=:n");

      

will always return one line with the account number, so

$rows = $result->fetchAll; 

      



will always return one.

You can do like

$result = $pdo->prepare("select count(*)  as tot from rum where nummer=:n");
....
....
$rows = $result->fetchAll(); 
if($rows["tot"] > 0 ){
  echo 'something'
}else{
  echo 'something else'
}

      

+1


source


just use fetch()

insteadfetchAll()

$rows = $result->fetch();
if($rows[0]) >1) {
   echo "1";
} else {
   echo "0";
} 

      

+1


source


Use PDOStatement::fetchColumn()

. It is useful for "single column" result sets (which are relatively common with type queries SELECT COUNT(...) FROM ...

). Example:

$nummer = isset($_GET['nummer']) ? $_GET['nummer'] : null;

$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare('SELECT COUNT(*) FROM rum WHERE (nummer = :n)');
$stmt->bindParam(':n', $nummer, PDO::PARAM_INT);
$stmt->execute();

$rows = $stmt->fetchColumn();

echo $rows > 1 ? "1" : "0";

      

0


source







All Articles