When I run this code I expect “I’m sorry, there seems to be a problem.” but I get “2013”
if ( $stmt = $PDO->query("SELECT COUNT(show) FROM shows WHERE on_year = $current_year ") ){
echo "$current_year";
}
else { echo "<p>Toylander will be attending some shows in $current_year.<br>Dates to be confirmed</p>"; }
}
The only way I can get what I want is by using:
if ( ($stmt = $PDO->query("SELECT COUNT(show) FROM shows WHERE on_year = $current_year ")) >= 2 ){
echo "$current_year";
}
else { echo "<p>Toylander will be attending some shows in $current_year.<br>Dates to be confirmed</p>"; }
}
Obviously I am doing something wrong; can somebody let me know what it is!
Out of interest the same thing was happening when I was using Mysql statements.
You should get an error when you compare that object against an int as your’re doing (E_NOTICE: Object of class PDOStatement could not be converted to int).
Probably you have those disabled? Might want to enable them in php.ini as it saves a lot of head aches to see notices, at least in development environments (never on production!)
Since you’re not getting an error I’m assuming PHP is comparing the 2 to the resource number of the PDOStatement object or something like that, which is rather dirty and can’t be relied upon.
$res = $PDO->query("SELECT COUNT(show) FROM shows WHERE on_year = $current_year"));
if ($res->fetchColumn() > 0) {
echo "$current_year";
} else {
echo "<p>Toylander will be attending some shows in $current_year.<br>Dates to be confirmed</p>";
}
or, even better
$stmt = $PDO->prepare("SELECT COUNT(show) FROM shows WHERE on_year = ?"));
$stmt->execute(array($current_year)); // or $stmt->execute([$current_year']); if you're on PHP>=5.4
if ($stmt->fetchColumn() > 0) {
echo "$current_year";
} else {
echo "<p>Toylander will be attending some shows in $current_year.<br>Dates to be confirmed</p>";
}
Thanks for the info @ScallioXTX and I have tried both your examples without success and am getting an internal server error.
I am getting a bit tired now and will have a look at it again tomorrow.
I based my second code snippet above on a user submitted example from the php site and I modified it slightly; but only in the if loop. I can not find the page again now.
// or $stmt->execute([$current_year’]); if you’re on PHP>=5.4
This is annoying as my code will break when the hosts update to that php version. I suppose everybody will have to rewrite their code then!
Update:
Server error due to an extra ) on this line:
$stmt = $PDO->prepare("SELECT COUNT(show) FROM shows WHERE on_year = ?"));
You don’t have to change array(something) to [something], as array(something) will still work; is just a different notation for array() since PHP 5.4, so I just added that if you’re on PHP 5.4 you might want to use that
In fact, your code probably won’t work on < 5.4 because the compiler doesn’t recognise the syntax.