FOREACH 和 UPDATE mysql 不起作用


FOREACH and UPDATE mysql not working

我有一个选择查询,然后在foreach循环中有一个更新查询。

我可以从选择中获取数据,并将其用作 json 来绘制图表,但对于应该使用来自 select 的相同数据更新的另一个表,指定的文件变为 0 有时为 1 或 2 !!
我尝试使用选择进行更新,它可以(更新....(选择....))但是在里面它不起作用。我也尝试使用其他列,但结果相同,总是得到 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();
}
 $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"' );

现在试试这个。

您正在使用 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'] . '"');

而且您应该使用查询构建器,正如亚历克斯所建议的那样,这是非常安全的

最后我使用了这段代码

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.');
}
}

谢谢大家