拼接sql语句参数绑定

 /**
* 事务封装方法
* @access public
* @param array $sqls 要执行的sql数组或语句
* @return boolean
*/
public function transExecuteSql($sqls, $vals) {
try {
$this->startTrans();
if (is_array($sqls)) {
foreach ($sqls as $k => $sql) {
if (!isNull($vals)) {
foreach ($vals[$k] as $valKey => $val) {
$sql = $this->bindParam($sql, $valKey + 1, $val);
}
}

$result = $this->db->execute($sql);
if ($result === false) {//update 数据和原来如果一样的话返回的是0
// if(!$result)
$this->rollBack();
return false;
}
}
} else {
$result = $this->db->execute($sqls);
if (!$result) {
$this->rollBack();
return false;
}
}
$this->commit();
return true;
} catch (\Exception $e) {
$this->rollBack();
//
$sxLog = new \Org\Log\SXLog();
$sxLog->recordSqlLogger($e);
return false;
}
}

/**
* 绑定参数过程
*
* @param string $sql SQL语句
* @param int $location 问号位置
* @param mixed $var 替换的变量
* @param string $type 替换的类型
*/
public function bindParam(&$sql, $location, $var, $type = 'STRING') {
switch ($type) {
//字符串
default: //默认使用字符串类型
case 'STRING' :
$var = addslashes($var); //转义
$var = "'" . $var . "'"; //加上单引号.SQL语句中字符串插入必须加单引号
break;
case 'INTEGER' :
case 'INT' :
$var = (int) $var; //强制转换成int
//还可以增加更多类型..
}
//寻找问号的位置
//for ($i=1, $pos = 0; $i<= $location; $i++) {
$pos = strpos($sql, '?', $location + 1);
//}
//替换问号
$sql = substr($sql, 0, $pos) . $var . substr($sql, $pos + 1);

return $sql;
}
posted @ 2017-04-12 23:01  (BACH)  阅读(614)  评论(0编辑  收藏  举报