php - 新手问题: PDO and MYSQL INSERT Query problem

标签 php mysql pdo

我正在尝试更加安全并开始使用 PDO 和准备好的语句。这是向我推荐的,我已经在这两个网站上阅读过: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/http://webdevrefinery.com/forums/topic/1272-your-mysql-code-sucks

我碰壁了,我不明白为什么以下内容不起作用。我正在尝试插入一行(以记录 404 错误)。我已经阅读了有关命名和未命名占位符的信息,我认为命名占位符方法更易于维护。我也第一次尝试使用“try”和“catch”。所有这些对我来说都是全新的,所以请善待!我没有收到任何错误,但代码没有更新数据库 - 我返回了零行。

代码如下:

$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();  
}  



?>

最佳答案

您确定表名是 404s 吗?这听起来像是一个不正确的标识符。

 INSERT INTO 404s (dateTime, referer, page, ip, host, ua) value (:dateTime, :referer, :page, :ip, :host, :ua)

尝试:

 INSERT INTO `404s` (dateTime, referer, page, ip, host, ua) value (:dateTime, :referer, :page, :ip, :host, :ua)

`404s` 周围使用反引号

注意 请记住,构造如:

create table `404` ( `33` integer);

有效。

当您构建复杂的请求时,使用 ` 对于避免某种痛苦的 SQL 错误非常有用,尤其是当您从内省(introspection)算法格式化请求时。

像表、列和数据库一样需要保护。

关于php - 新手问题: PDO and MYSQL INSERT Query problem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6357642/

相关文章:

mysql - http ://java. sun.com/jsp/jSTL/core 无法在 web.xml 或随此应用程序部署的 jar 文件中解析

mysql - 需要访问由条件定义的表的字段

php - 如何在不使用 URL 中的 .php 的情况下访问 php 页面

php - 阿拉伯语中的 Sphinx Search 2.2.5 不工作

java - 连接数据库时出错 : Cannot create JDBC driver of class '' for connect URL 'null'

PHP、MySQL、PDO - 插入不工作

php - pdo mysql 数据检索

mysql_ -> PDO |我怎样才能达到相同的结果

php - PHP 是否具有与 Java 的 RequestDispatcher.forward 等效的功能?

php - 如何在 Yii Framework 中进行记录计数?