由于我在服务器上将PHP更新为PHP5.5,所以我想使用PDO而不是mysql_重写一个项目。
在这个项目中,我有一个控制器和一个模型(当然也有一个视图,但这并不重要:-))
在“旧”版本中,代码如下所示:
控制器(mysql)
public function saveAction()
{
$iFilterID = filter_input(INPUT_POST, 'id');
$this->_setRealEscape($iFilterID);
$iReqID = $this->_getRealEscape();
if (isset($_REQUEST['aLinks']))
{
$this->oSubCat = new links ();
if (isset($iFilterID))
{
$this->oSubCat->loadLinksID($iReqID);
}
foreach ($_REQUEST['aLinks'] AS $key => $value)
{
$value = $this->_cleanString($value);
$this->oSubCat->$key = $value;
}
}
$this->oSubCat->saveLinks();
}
模型(mysql)
public function loadLinksID($id)
{
$sSql = "SELECT * FROM links WHERE id =".$id;
$query = mysql_query($sSql);
$oLinks = mysql_fetch_object($query);
if(is_object($oLinks))
{
foreach ($oLinks as $key => $value)
{
$this->$key = $value;
}
}
}
public function saveLinks ()
{
if ($this->id)
{
$this->updateLinks();
}
else
{
$this->insertLinks();
}
}
public function updateLinks ()
{
$sSql = "UPDATE links SET";
$first = true;
foreach ($this as $property => $value) {
if ($first) {
$first = false;
$sSql .= " $property='$value'";
} else {
$sSql .= ", $property='$value'";
}
}
$sSql .= " WHERE id = ".$this->id;
mysql_query($sSql);
header("location: index.php?module=helper&action=success&func=links");
}
在PDO版本中,如下所示:
控制器(PDO)
public function saveAction()
{
$iFilterID = filter_input(INPUT_POST, 'id');
if (isset($_REQUEST['aLinks']))
{
$this->oSubCat = new links ();
if (isset($iFilterID))
{
$this->oSubCat->loadLinksID($iFilterID);
}
foreach ($_REQUEST['aLinks'] AS $key => $value)
{
$this->oSubCat->$key = $value;
}
}
$this->oSubCat->saveLinks();
}
模型(PDO)
public function loadLinksID($id)
{
$PDOpre = $this->connection->prepare("SELECT * FROM links WHERE id =:id");
$PDOpre->bindvalue(':id',$id, PDO::PARAM_STR);
$PDOpre->execute();
$oLinks = $PDOpre->fetch(PDO::FETCH_OBJ);
if(is_object($oLinks))
{
foreach ($oLinks as $key => $value)
{
$this->$key = $value;
}
}
}
public function saveLinks ()
{
if ($this->id)
{
$this->updateLinks();
}
else
{
$this->insertLinks();
}
}
public function updateLinks ()
{
$sSql = "UPDATE links SET";
$first = true;
foreach ($this as $property => $value) {
if ($first) {
$first = false;
$sSql .= " $property='$value'";
} else {
$sSql .= ", $property='$value'";
}
}
$sSql .= " WHERE id = ".$this->id;
echo $sSql;
$this->connection->query($sSql);
header("location: index.php?module=helper&action=success&func=links");
}
mysql_-Version运行良好,但PDO版本显示:
可捕获的致命错误:类PDO的对象无法转换为/中的字符串/第61行的httpdoc/new/model/class.links.php
第61行=
$sSql .= " $property='$value'";
在公共函数updateLinks()中
我对PDO完全陌生,现在它已经让我不知所措了。
有人能给我一个正确的方向,如何解决这个问题吗。
非常感谢您的帮助。
提前感谢
做记号