Reputation: 43
So I'm trying to use PDO objects on my site instead of the old method (especially since I heard it is better for and am in the process of updating a bunch of queries. But for some reason, I can not get prepare/execute to work no matter what I do.
dbconnect.php:
try {
$main = new PDO("mysql:dbname=$dbmain;host=$dbhost", $dbuser, $dbpassword);
$tracker = new PDO("mysql:dbname=$dbtracker;host=$dbhost", $dbuser, $dbpassword);
} catch (PDOException $ex) {
echo "Connection failed: " . $ex->getMessage();
}
tracker.php
include 'dbconnect.php';
$page = $_SERVER['PHP_SELF']; //Get page name
$ip = $_SERVER['REMOTE_ADDR']; //Get the IP address
$browser = $_SERVER['HTTP_USER_AGENT']; //Get the browser name
if(isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER']; //Get the page the visitor came from
}
else { //If not refered from any page, referer should be blank or error occurs
$referer = "";
}
$result = $tracker->prepare("INSERT INTO 'pages' ('page', 'ip', 'browser', 'referer') VALUES (:page, :ip, :browser, :referer)");
$result->execute(
array(
':page' => $page,
':ip' => $ip,
':browser' => $browser,
':referer' => $referer
)
);
Secondly, could someone explain to me why I shouldnt use query() for everything? Right now I see that I should use query for non-dynamic queries, and prepare/execute for dynamic, but query works for both.
Thanks!
Upvotes: 1
Views: 5875
Reputation: 263723
The problem I see (may could have other problem) is you are wrapping column names with single quotes. Column names and Table names are identifiers not string literals. If ever you have used a reserved keyword on them or the column name as well as table names contains spaces around them, they should be escaped with backtick not with single quote,
INSERT INTO pages (page, ip, browser, referer) VALUES (...)
Upvotes: 2