【发布时间】:2014-03-25 07:06:49
【问题描述】:
我正在尝试使用 PDO 插入数据库,但在完成脚本并对其进行测试后,我没有看到插入数据库的任何类型的输入,我尝试从 PDO 返回错误但什么也没有。我不确定发生了什么
我已经更新了参数名称,它们似乎并没有改变代码结果。似乎 q() 函数只是有问题。
数据库已初始化,如下所示:
function __construct() {
if ( ! file_exists( dbpath . DB ) ) {
$this->db = true;
$this->open( dbpath . DB, SQLITE3_OPEN_CREATE|SQLITE3_OPEN_READWRITE ) or $this->db = false;
if ( $this->db == false ) {
return false;
}
$table = "CREATE TABLE link_hits( id INTEGER PRIMARY KEY AUTOINCREMENT, link TEXT NOT NULL, hits INT NOT NULL, date_added datetime default current_timestamp)";
$this->exec($table);
} else {
$this->db = true;
$this->open( dbpath . DB, SQLITE3_OPEN_CREATE|SQLITE3_OPEN_READWRITE ) or $this->db = false;
if ( $this->db == false ) {
return false;
}
}
}
准备语句函数
function q ( $q, $v ) {
if ( $this->db ) {
$this->securedb = $this->prepare( $q );
foreach ( $v as $k=>$vv ) {
if ( is_numeric( $vv ) ) {
$this->securedb->bindValue($k, $vv, SQLITE3_INTEGER);
} else {
$this->securedb->bindValue($k, $vv, SQLITE3_TEXT);
}
}
$this->errorInfo = $this->errorInfo();
return ( ( $this->handle = $this->execute() ) == true ) ? $this->handle : false;
}
return false;
}
添加链接功能
function addlink ( $link ) {
if ( $this->linkexists( $link ) ) {
return false;
}
$this->que = "INSERT INTO link_hits (link, hits) VALUES (:link, :hits)";
$this->input = array(
':link' => $link,
':hits' => 0
);
return ( $this->q( $this->que, $this->input ) ) ? true : false;
}
我的陈述是否正确?我遵循了几个教程。我真的习惯了 MySQL,但无法访问它。 :(
即使我的 linkexists 函数也会抛出错误。是的,链接在那里,我用普通查询强制它。
function linkexists( $link ) {
$this->que = "SELECT link FROM link_hits WHERE type='table' AND link=':link'";
$this->input = array(
':link' => $link
);
return ( ( $this->handle = $this->q( $this->que, $this->input ) ) == true ) ? true : false;
}
【问题讨论】:
-
为什么要在绑定变量旁边附加
;? -
在几个例子中看到了。这只是一种模式,任何东西都可以使用 IE *{|}*key;:; ...至少据我所知。
-
linkexists中的语句有很多引号; PDO 会自动插入这些。试试这个:SELECT link FROM link_hits WHERE type=:type AND link=:link- 但对于你的主要问题,我不知道。 :) -
谢谢,但它仍然会抛出同样的错误。无论哪种方式,它都是多余的。甚至用于检查表是否存在的 PDO 文档也使用此标记,包括半引号。