insert语句不写入sqlite 3中的db文件?

时间:2011-08-19 18:28:28

标签: php sqlite insert

我正在尝试将数据从简单的表单写入SQLite数据库,但即使我提交了事务,也没有任何内容写入数据库文件。这是php代码:

$expense = new Model();
$expense->add_expense($_POST);

并在Model类中:

class Model {

    private $database = 'expenses.db';
    private $dbh;

    function __construct() {
        $this->dbh = new PDO('sqlite:/var/www/expenses/' . $this->database);
        $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public function add_expense($args) {
        $stmt = $this->dbh->prepare('INSERT INTO `expenses` (`type`, `name`, `location`, `receipt_date`, `price`, `notes`) VALUES (?, ?, ?, ?, ?, ?)');
        $this->dbh->beginTransaction();
        $stmt->execute(array_values($args));
        $this->dbh->commit();     
    }
}

这是$args的内容,来自函数内部:

Array
(
    [type] => type
    [name] => item_name
    [location] => place
    [date] => 1313180040
    [price] => 8.86
    [notes] => none
)

此外,$stmt->getMessage();不会输出任何内容。这是创建表的SQL:

BEGIN TRANSACTION;
CREATE TABLE expenses (notes TEXT, type TEXT, location TEXT, name TEXT, price NUMERIC, receipt_date NUMERIC);
COMMIT;

验证无关紧要,所以我把它遗漏了。我列出的$args的内容是在验证之后发生的,并且它都是正确的。

更新:相同的代码,但改为使用bindParam和命名参数:

$stmt = $this->dbh->prepare('INSERT INTO `expenses` (`type`, `name`, `location`, `receipt_date`, `price`, `notes`) VALUES (:type, :name, :location, :receipt_date, :price, :notes)');

和绑定声明:

$stmt->bindParam(':type', $args['type']);
$stmt->bindParam(':name', $args['name']);
$stmt->bindParam(':location', $args['location']);
$stmt->bindParam(':receipt_date', $args['date']);
$stmt->bindParam(':price', $args['price']);
$stmt->bindParam(':notes', $args['notes']);
$stmt->execute();

仍然没有任何反应。

2 个答案:

答案 0 :(得分:1)

解决了它;命令sqlite3 expenses.db使用我的linux用户帐户作为所有者创建了数据库,但php脚本通过Web服务器运行,因此所有者是www-data。我更改了所有权和权限,现在工作正常。谢谢你的帮助!

答案 1 :(得分:0)

但是即使是命令行sqlite3也有问题,所有者脚本给所有者db写道: 即:sqlite> INSERT INTO作者(姓名)VALUES('Hugh MacDairmid'); 只有在用su(或使用sudo)打开终端后才会发生数据库写入。 我想这不应该是一个惊喜。