This is an example of the type of query I use to display dynamic web pages. This particular query is associated with a website/section that displays URL’s like MySite/People/Don_Juan, where Don_Juan = both $MyURL and a value in the field URL, table people…
$res = mysql_query("SELECT COUNT(URL)
FROM people
WHERE URL = '$MyURL' AND Site = 'PX'
OR '$MyURL' = CONCAT('Washington/', URL) AND Site = 'SM'");
if (!$res) {
die('Invalid query: ' . mysql_error());
}
$result = mysql_result($res, 0);
// PART 2 - Interpret the results...
switch ($result)
{
case 1:
// include related files
break;
case 0:
// include 404 NOT FOUND error message
break;
default:
// multiple entries; deal with as needed
break;
}
Now I’m trying to figure out how to convert this to a PDO query. Since COUNT is the simplest query, I thought it would be the easiest to convert. To my surprise, many online references say PDO can’t perform COUNT queries. As I understand it, all the PDO queries that do this sort of thing are workarounds.
Anyway, I’ve tried several PDO scripts, but nothing works.
I start out with my PDO database connection (replacing “USERNAME” and “PASSWORD” with my username and password, of course…
try {
$db = new PDO('mysql:host=localhost;dbname=db_new;charset=utf8', 'USERNAME', 'PASSWORD');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
The above code is on a separate file that’s included in every page on my website.
Next comes this code…
$sql= "SELECT URL FROM people
WHERE URL = '$MyURL'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$total = $stmt->rowCount();
But it doesn’t work, and there’s no error message to indicate what the problem is. (However, if I modify my username or password in the connection script, I do get an error message referring to my database connection.) Once I do get it to work, I assume I can finish the job by simply replacing $result with $total…
switch ($total)
{
case 1:
// include related files
break;
case 0:
// include 404 NOT FOUND error message
break;
default:
// multiple entries; deal with as needed
break;
}
So can anyone tell me what’s wrong with my code? Or should I be using a different script altogether?
Thanks.