Isador
Isador

Reputation: 603

PHP function returns always 1

I have a model function to check if pseudo_exist in my DB :

<?php
function pseudo_check($DB, $pseudo) {

    $req = $DB->prepare("SELECT COUNT(pseudo) FROM members where pseudo = ?");

    $req -> execute(array($pseudo));
    $nbre_pseudo = $req->fetch();

    settype($nbre_pseudo, "integer");

    $path = "LOG.txt";
    $ressource = fopen($path, "a");
    fwrite($ressource, "$nbre_pseudo");
    fclose($ressource);

    return ($nbre_pseudo);
    $req->closeCursor();
}
?>

Then, I call my function with a controller file :

<?php
require_once('models/dbconnect.php');
require_once('models/inscription_functions.php');

pseudo_check($DB, $_POST['pseudo']);

if($nbre_pseudo > 0)
{
    header('location: index.php?page=inscription&error=pseudo_exist');
}
?>

Thanks.

Upvotes: 0

Views: 52

Answers (2)

aergistal
aergistal

Reputation: 31209

Using settype($nbre_pseudo, "integer") you are converting an array to an integer. The result is either 0 if the array is empty or 1 if the array is not empty.

Upvotes: 1

Kevin Nelson
Kevin Nelson

Reputation: 7663

If you are doing settype to prevent an array returning...setting type on an array is not the same as getting the value out of the array.

$req = $DB->prepare("SELECT COUNT(pseudo) AS count FROM members where pseudo = ?");

$req -> execute(array($pseudo));
$nbre_pseudo = $req->fetch();

$count = $nbre_pseudo['count']

Upvotes: 1

Related Questions