framework1.1.8dbCDbCommand.php
最近写了个小工具来实现绑定。发现一个小问题 -.- !
/** * 纯sql自动过滤 * * @author caihaibin * @param string $sql * @param array $params * array(':id'=>33) * @param boolean $showError * 表示是否打印sql错误信息 * @throws Exception */ function sql_execute_bind($sql, $params = array(), $showError = true, $mult = false) { try { if ($mult) { foreach ( $sql as $subsql ) { $db = Yii::app ()->db; $cmd = $db->createCommand ( $subsql ); if ($params) foreach ( $params as $k => $v ) { $cmd->bindParam ( $k, $v ); } $cmd->execute (); } } else { $db = Yii::app ()->db; $cmd = $db->createCommand ( $sql ); if ($params) foreach ( $params as $k => $v ) { $cmd->bindParam ( $k, $v ); } $cmd->execute (); } } catch ( Exception $e ) { if ($showError) echo $e->getMessage (); else { throw $e; } } }
$v 在循环的过程中,为同一个地址的变量.
bindParam的值引用为地址。导致前面参数会被后面的绑定参数所覆盖
函数名
public function bindParam($name, &$value, $dataType=null, $length=null, $driverOptions=null)
解决方式,让$v使用原来的地址即可,即&$v
/** * 纯sql自动过滤 * * @author caihaibin * @param string $sql * @param array $params * array(':id'=>33) * @param boolean $showError * 表示是否打印sql错误信息 * @throws Exception */ function sql_execute_bind($sql, $params = array(), $showError = true, $mult = false) { try { if ($mult) { foreach ( $sql as $subsql ) { $db = Yii::app ()->db; $cmd = $db->createCommand ( $subsql ); if ($params) foreach ( $params as $k => &$v ) { $cmd->bindParam ( $k, $v ); } $cmd->execute (); } } else { $db = Yii::app ()->db; $cmd = $db->createCommand ( $sql ); if ($params) foreach ( $params as $k => &$v ) { $cmd->bindParam ( $k, $v ); } $cmd->execute (); } } catch ( Exception $e ) { if ($showError) echo $e->getMessage (); else { throw $e; } } }
补充:
http://www.laruence.com/2012/10/16/2831.html
http://weibo.com/1170999921/ylgFcpe1f
示例代码:
$arr=range(1,3); var_dump($arr); foreach($arr as &$val){ } var_dump($arr); //解决方式 参考:http://www.php.net/manual/zh/control-structures.foreach.php //unset($val); // 最后取消掉引用
注:引用方式和原先所思考有所出入,需要查证后再做说明
验证:
$arr=range(1,3); var_dump($arr); foreach($arr as &$val){ if($val==2) break; } var_dump($arr);
为当前变量,传递引用地址。不过php出循环的时候。。竟然没还保留。导致不小心修改了$val
如:$val =3;在foreach 之后。会导致数据被修改.
转发请注明出处http://blog.martoo.cn
如有漏缺,请联系我 QQ 243008827