FOREACH和UPDATE mysql无法正常工作

时间:2013-01-29 11:38:15

标签: php mysql foreach yii sql-update

我有一个select查询,后跟foreach循环中的更新查询。

我可以从select中获取数据并将其用作json来绘制图表,但是对于应该使用select中的相同数据更新的另一个表,指定的字段有时变为0或1或2 !!登记/> 我试图使用选择更新,它确定(更新....(选择....))但在foreach内部它不起作用。 我也尝试使用其他列但结果相同,总是得到0。 有什么好主意吗? 非常感谢提前

这是我的代码

public function actionGetSensorsDataLive($beamId) {
    header('Content-Type: application/json; charset="UTF-8"');
    $sensorsIds = Sensor::model()->findAllBySql('SELECT sensor_id FROM sensor where 
                             node_id="' . $beamId . '" and sensor_name = "I" ;');

    foreach ($sensorsIds as $s) {
        $sResult = array();
       $modelSensor = SensorInfo2::model()->findBySql('SELECT * FROM information_sensor  
             where sensor_id= "' . $s['sensor_id'] . '"');

        $sResult = array(($modelSensor->information_sensor_time),
            ($modelSensor->information_sensor_value));
        /////////////// update//////////////// 
        // for every information_sensor_time that I get from the previous query  
         //  I want
        //  to update a row in another table //

        foreach ($modelSensor as $up) {
            $connection = yii::app()->db;

            $sql = 'UPDATE last_point  SET last_point_time = "' . 
                             $up['information_sensor_time'] . '"
            WHERE sensor_id= "' . $s['sensor_id'] . '"  ';

            $command = $connection->createCommand($sql);
            $command->execute();
        }
        /////update end///////               
    }
    echo json_encode($sResult);
    Yii::app()->end();
}

3 个答案:

答案 0 :(得分:0)

 $sensorsIds=Sensor::model()->findAllBySql('SELECT sensor_id FROM lead where 
                         node_id="'.$beamId.'" and sensor_name = "I" ;' );

删除;

 $sensorsIds=Sensor::model()->findAllBySql('SELECT sensor_id FROM lead where 
                         node_id="'.$beamId.'" and sensor_name = "I"' );

现在尝试一下。

答案 1 :(得分:0)

你正在使用findBySql()`它只返回一条记录,然后在tha上做foreach是没有意义的。所以行了

 $modelSensor = SensorInfo2::model()->findBySql('SELECT * FROM information_sensor  
             where sensor_id= "' . $s['sensor_id'] . '"');

$modelSensor = SensorInfo2::model()->findAllBySql('SELECT * FROM information_sensor  
             where sensor_id= "' . $s['sensor_id'] . '"');

你应该使用如Alex建议的那么安全的querybuilder

答案 2 :(得分:0)

最后我使用了这段代码

foreach ($sensors as $sensor)  {
$lastPointId = 1;  
$lastPoint = LastPoint::model()->findByPk($lastPointId);
$lastPoint->last_point_info = $sensor->information_time;
if ( ! $lastPoint->save()) {
    throw new CException('Unable to save last point.');
}
}

全部谢谢