Question

public function checkIfTeamExists($team) {
    $array = array();
    try {
        $sth = $this -> db -> prepare("SELECT * FROM teams WHERE Name = :team");
        $sth -> execute(array(':team' => $team));
        foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $array[] = $row;
        }
        return $array;
    } catch (Exception $e) {
        header('Location: /error');
    }
}

index.php

$URL = explode("/", $_SERVER['REQUEST_URI']);
$teamName = $URL[2];
$teamExists = $db -> checkIfTeamExists($teamName);
$teamExists = (count($teamExists) > 0);
print $teamExists;exit();
if ($teamExists) {
    $teamNameUpper = ucwords(strtolower($teamName));
}
else {var_dump($teamExists);}

Let's set the URL to localhost/team/Bulls.

$URL[2], in that case, is "Bulls."

$teamExists = $db -> checkIfTeamExists($teamName); would set the value of $teamExists to an array.

Next, $teamExists = (count($teamExists) > 0); would set the value of $teamExists to "true" (in this case, it's true because "Bulls" does exist in the DB).

Here is where the problem comes: As you can see on line 5, print $teamExists;exit(); is there. It prints 1, which is the expected result. However, if I take away the exit() part and let the script run as is, it only executes the "else" part of the if-else condition. Which must mean that the value of $teamExists has changed from 1.

I am unable to understand what I am doing wrong. How can the value change like that?

Était-ce utile?

La solution

To be really fussy I'd be changing the query in the function to "select count..., then test to see if the answer was > 0 and return true or false. Your main script would then be

$URL = explode("/", $_SERVER['REQUEST_URI']);
$teamName = $URL[2];
$teamExists = $db -> checkIfTeamExists($teamName);

var_dump($teamExists);exit();
if ($teamExists) {
    $teamNameUpper = ucwords(strtolower($teamName));
}
else {var_dump($teamExists);}

I've changed the print to a var_dump but pretty much anything that isn't false should still be true. I'd be interested to know what you get from the var_dump though.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top