Yii DAO上的NULL而不是值SQL INSERT:bindValue

时间:2011-11-09 22:11:10

标签: php sql yii

我有行动:

项目控制器中的

更新操作。在项目/视图/#

中从ajaxLink调用的操作
public function actionAddInterest() {
            $itm= Item::model()->find("`ItemId` = :itm", array(':itm' => $_GET['ItemId']));
            $connection = yii::app()->db;
            $sql1 = "INSERT INTO interest (UserId, ItemId)
                        VALUES(:usr, :itm)";
            $command=$connection->createCommand($sql1);

            $command->bindValue(":usr", Yii::app()->user->id);
            $command->bindValue(":itm", $itm);
            $command->execute();
        } 

我也试过转储变量并通过firebug响应这个...返回NULL。所以有些东西不适用于$ _GET。

$itm= Item::model()->find("`ItemId` = :itm", array(':itm' => $_GET['ItemId']));
var_dump($itm);
die();

ORIGINAL

 public function actionAddInterest() {
        $model = new Item;
        $connection = yii::app()->db;
        $sql1 = "INSERT INTO interest (UserId, ItemId)
                    VALUES(:usr, :itm)";
        $command=$connection->createCommand($sql1);

        $command->bindValue(":usr", Yii::app()->user->id);
        $command->bindValue(":itm", $model->ItemId);
        // $command->bindValue(":itm", $model->ItemId, PDO::PARAM_INT);  //also tried
        $command->execute();
    } 

虽然没有从$model->ItemId捕获值,但它为输入返回NULL。我在这里错过了什么?

3 个答案:

答案 0 :(得分:2)

感谢大家的帮助。

这里要完成的是解决方案..

我必须添加

'data' => array('ItemId' => $model->ItemId),

<?php 
  echo CHtml::ajaxLink(
    'Add Interest',          
    array('/item/addInterest'), 
    array(
      'data' => array('ItemId' => $model->ItemId),
      'update'=>'#int_res'
      )
  );
?>

这是调用操作的ajaxLink。

答案 1 :(得分:0)

你有     $ model = new Item; 所以它的新对象,它还没有任何数据库ID。您必须先为此$ model

添加值
$model->label = "Abc";
$model->someMore = "val";

并保存

if ( $model->save() ) { 
    //get ID
    $itemId = app()->db->getLastInsertID();
}

或者我错过了你的任务?

答案 2 :(得分:0)

如果您想从页面上的表单中捕获ItemId,可以使用:

if (!isset($_POST['Item']))
    Yii::app()->end();

$model = new Item;
$model->attributes = $_POST['Item'];

...

并使用$ model-&gt; ItemId

但是,您应该使用提交表单按钮请求此操作。 因为在另一种情况下不会有表单数据($ _POST ['Item'])。