dimanche 23 juillet 2017

Unusual behavour in PHP IF construction

I know there´s something really simply I´m doing wrong here but I´ve been playing around with things for hours now, without seeing what´s wrong. The original code would just output the number of rows counted, but somehow it only gave an output when the number was higher than 0. So instead I changed it to something where I thought couldn´t go wrong, but still the result is the same. This is the code:

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, 
$password);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);  
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$usernametmp = $_GET["usernametmp"]; 
$code = $_GET["code"];
$response = "0";
$stmt = $conn->prepare("SELECT * FROM Users WHERE (username = ?) AND 
(code =?)  limit 1");
$stmt->execute(array($usernametmp,$code));

foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as 
$k=>$v) {}
if ($stmt->rowCount() > 0) 
{
$response = ($stmt->rowCount());
}
echo ($response);
}

Now, the REALLY weird thing is that if I add echo ($response) right after it´s been set to 0 in $response = "0", so that echo ($response) occurs twice, things do what they´re supposed to: When no rows are found, it echos 00, and when a row is found, it echos 01! Of course I could just leave it there, and use the 2nd character to determine the result, but I think it´s important to understand the underlying problem here.

Any ideas?

Aucun commentaire:

Enregistrer un commentaire