I'm attempting to be more secure and start using PDO and prepared statements. This had been recommended to me and I've read up on these two websites: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/ and http://webdevrefinery.com/forums/topic/1272-your-mysql-code-sucks
I've hit a brick wall and I can't understand why the following doesn't work. I am trying to insert a row (to log a 404 error). I have read up about named and unnamed placeholders and I think the named placeholder method will be easier to maintain. I've also tried using "try" and "catch" for the first time. All of this is completely new to me, so please be kind! I don't get any errors but the code doesn't update the database- I get zero rows returned.
Here is the code:
$referer = $_SERVER['HTTP_REFERER'];
$domainName = "http://domain.com";
$_dtNow = date("d-m-Y H:i:s");
$_referer = $domainName.$_SERVER['REQUEST_URI'];
$_thisPage = $domainName.$url;
$_ip = $_SERVER['REMOTE_ADDR'];
$_host = $_SERVER['REMOTE_HOST'];
if(isset($_SERVER['HTTP_USER_AGENT'])) {$_ua = $_SERVER['HTTP_USER_AGENT'];} else {$_ua = "unset";}
$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = 'databaseName';
$username = 'username';
$password = 'password';
// Construct the DSN, or "Data Source Name". Really, it's just a fancy name
// for a string that says what type of server we're connecting to, and how
// to connect to it. As long as the above is filled out, this line is all
// you need :)
$dsn = "mysql:host=$host;port=$port;dbname=$database";
try {
// Connect!
$db = new PDO($dsn, $username, $password);
$data = array(
'dateTime' => $_dtNow,
'referer' => $_referer,
'page' => $_thisPage,
'ip' => $_ip,
'host' => $_host,
'ua' => $_ua
);
$statement = $db->prepare("INSERT INTO 404s (dateTime, referer, page, ip, host, ua) value (:dateTime, :referer, :page, :ip, :host, :ua)");
$statement->execute($data);
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>