【发布时间】:2014-06-17 13:41:35
【问题描述】:
我无法用 PDO 的 PHP 对象和从 JSON 文件创建的对象填充表。你看到错误来自哪里了吗? 我使用 PHP5 和 PostgreSQL
我写的代码成功添加了行,但是每行只有第一列(字段)被填充,其他保持白色。
我的表结构如下:
CREATE TABLE ' . $infoTableName . ' (field text,type text,expefactor boolean,iduser boolean,idcontext boolean,idaction boolean,params boolean,comment text)
我的对象如下所示:
object(stdClass)[3]
public 'timestamp' =>
object(stdClass)[4]
public 'idagent' => boolean false
public 'idcontext' => boolean false
public 'idaction' => boolean false
public 'comment' => string 'ffff' (length=4)
public 'order' =>
object(stdClass)[5]
public 'idagent' => boolean false
public 'idcontext' => boolean false
public 'idaction' => boolean false
public 'comment' => string 'none' (length=4)
public 'test' =>
object(stdClass)[6]
public 'idagent' => boolean false
public 'idcontext' => boolean true
public 'idaction' => boolean false
public 'comment' => string 'y' (length=1)
最后是 PHP 代码:
$structure = json_decode($_POST['structure']);
$query = "INSERT INTO " . $infoTableName . " (field, iduser, idcontext, idaction, comment) VALUES (:field, :idagent, :idcontext, :idaction, :comment)"; //Prequery
$stmt = $db->prepare($query);
$stmt->bindParam(':field', $key);
$stmt->bindParam(':idagent', $value->idagent);
$stmt->bindParam(':idcontext', $value->idcontext);
$stmt->bindParam(':idaction', $value->idaction);
$stmt->bindParam(':comment', $value->comment);
foreach ($structure as $key => &$value) {
try {
var_dump($stmt->execute());
} catch (PDOException $e) {
var_dump($e->getMessage());
}
}
你看到错误了吗? 非常感谢。
编辑:看起来我对绑定函数中的对象提出了太多要求,不过,这里有一个小解决方法:
$stmt->bindParam(':field', $key);
$stmt->bindParam(':idagent', $idagent);
$stmt->bindParam(':idcontext', $idcontext);
$stmt->bindParam(':idaction', $idaction);
$stmt->bindParam(':comment', $comment);
foreach ($structure as $key => &$value) {
$idagent = $value->idagent;
$idcontext = $value->idcontext;
$idaction = $value->idaction;
$comment = $value->comment;
try {
var_dump($stmt->execute());
} catch (PDOException $e) {
var_dump($e->getMessage());
}
}
bindParam() 不起作用的原因是当我遍历 $structure 时,$value 被重新实例化,导致引用被更改...我首先认为 &$value 会有所帮助,但看起来没有。
【问题讨论】:
-
你试图在
$value被定义之前使用$value->......!? -
就像他们在这里做的那样:link 这是官方的 php 手册。也许这不适用于对象?
标签: php postgresql pdo