欢迎光临外链推广平台,一个优秀的外链推广平台,为你解决获客难题!

thinkphp 和 laravel使用sql语句操作db和源码浅析

作者:jcmp      发布时间:2021-05-04      浏览量:0
一、thinkphp$db=M();

一、thinkphp

$db=M(); $condition="XXX"; $sql="select student.id from student where `s_name`= '$condition'"; $result=$db->query($sql);

public function query($str,$fetchSql=false) { $this->initConnect(false); if ( !$this->_linkID ) return false; $this->queryStr = $str; if(!empty($this->bind)){ $that = $this; $this->queryStr = strtr($this->queryStr,array_map(function($val) use($that) { return '\''.$that->escapeString($val).'\''; } ,$this->bind)); } if($fetchSql){ return $this->queryStr; } //释放前次的查询结果 if ( !empty($this->PDOStatement) ) $this->free(); $this->queryTimes++; N('db_query',1); // 兼容代码 // 调试开始 $this->debug(true); $this->PDOStatement = $this->_linkID->prepare($str); if(false === $this->PDOStatement){ $this->error(); return false; } print_r($this->bind);//test foreach ($this->bind as $key => $val) { if(is_array($val)){ $this->PDOStatement->bindValue($key, $val[0], $val[1]); }else{ $this->PDOStatement->bindValue($key, $val); } } $this->bind = array(); $result = $this->PDOStatement->execute(); // 调试结束 $this->debug(false); if ( false === $result ) { $this->error(); return false; } else { return $this->getResult(); } }

public function escapeString($str) { return addslashes($str); }

////////其他都和query()一样 if ( false === $result) { $this->error(); return false; } else { $this->numRows = $this->PDOStatement->rowCount(); if(preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $str)) { $this->lastInsID = $this->_linkID->lastInsertId(); } return $this->numRows; } }

public function startTrans() { $this->initConnect(true); if ( !$this->_linkID ) return false; //数据rollback 支持 if ($this->transTimes == 0) { $this->_linkID->beginTransaction(); } $this->transTimes++; return ; } public function commit() { if ($this->transTimes > 0) { $result = $this->_linkID->commit(); $this->transTimes = 0; if(!$result){ $this->error(); return false; } } return true; } /** * 事务回滚 * @access public * @return boolean */ public function rollback() { if ($this->transTimes > 0) { $result = $this->_linkID->rollback(); $this->transTimes = 0; if(!$result){ $this->error(); return false; } } return true; }

$m->startTrans();$result=$m->where('删除条件')->delete();$result2=m2->where('删除条件')->delete();if($result && $result2){$m->commit();//成功则提交}else{$m->rollback();//不成功,则回滚}

$con['s_name']=$condition; $con['id']=3; $con['_logic'] = 'OR'; $field=array('id','s_name'); $db2=M('student'); $result2=$db2->where($con)->field($field)->select(); print_r($result2); $result3=$db2->getFieldBys_name('gbw2','id'); print_r($result3);

protected $options = array( PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_STRINGIFY_FETCHES => false, );

public function select($options=array()) { $this->model = $options['model']; $this->parseBind(!empty($options['bind'])?$options['bind']:array()); $sql = $this->buildSelectSql($options); $result = $this->query($sql,!empty($options['fetch_sql']) ? true : false); return $result; } /** * 生成查询SQL * @access public * @param array $options 表达式 * @return string */ public function buildSelectSql($options=array()) { if(isset($options['page'])) { // 根据页数计算limit list($page,$listRows) = $options['page']; $page = $page>0 ? $page : 1; $listRows= $listRows>0 ? $listRows : (is_numeric($options['limit'])?$options['limit']:20); $offset = $listRows*($page-1); $options['limit'] = $offset.','.$listRows; } $sql = $this->parseSql($this->selectSql,$options); return $sql; }/***中间省略*/ public function parseSql($sql,$options=array()){ $sql = str_replace( array('%TABLE%','%DISTINCT%','%FIELD%','%JOIN%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%','%UNION%','%LOCK%','%COMMENT%','%FORCE%'), array( $this->parseTable($options['table']), $this->parseDistinct(isset($options['distinct'])?$options['distinct']:false), $this->parseField(!empty($options['field'])?$options['field']:'*'), $this->parseJoin(!empty($options['join'])?$options['join']:''), $this->parseWhere(!empty($options['where'])?$options['where']:''), $this->parseGroup(!empty($options['group'])?$options['group']:''), $this->parseHaving(!empty($options['having'])?$options['having']:''), $this->parseOrder(!empty($options['order'])?$options['order']:''), $this->parseLimit(!empty($options['limit'])?$options['limit']:''), $this->parseUnion(!empty($options['union'])?$options['union']:''), $this->parseLock(isset($options['lock'])?$options['lock']:false), $this->parseComment(!empty($options['comment'])?$options['comment']:''), $this->parseForce(!empty($options['force'])?$options['force']:'') ),$sql); return $sql; }

protected function parseBind($bind){ $this->bind = array_merge($this->bind,$bind); }

//我们手动加上bind函数 $con['id']=':id'; $con['_logic'] = 'OR'; $field=array('id','s_name'); $db2=M('student'); $result2=$db2->where($con)->bind(':id',3)->field($field)->select(); //再在类中打印这个绑定的参数发现有了 print_r($this->bind);

二、leveral

$users = DB::table('users')->where('votes', '>', 100)->get();$result=DB::table('users')->select('name', 'email')->get();$goodsShow = DB::table('goods')->where([product_id'=>$id,'name'=>$name])->first();//同样可以使用原生的$db->select('select * from user where id in (?,?)', [$id,2]);$users = DB::table('users')->orderBy('name', 'desc')->groupBy('count')->having('count', '>', 100)->get();DB::table('users')->where('id', 1)->update(array('votes' => 1));

//先看看Illuminate\Database\Connectors\Connector.php protected $options = array( PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, PDO::ATTR_STRINGIFY_FETCHES => false, PDO::ATTR_EMULATE_PREPARES => false, );//初始化public function __construct(PDO $pdo, $database = '', $tablePrefix = '', array $config = array()) { $this->pdo = $pdo;....//先是DB::tablepublic function table($table) { $processor = $this->getPostProcessor(); $query = new Query\Builder($this, $this->getQueryGrammar(), $processor); return $query->from($table); }//selectpublic function select($query, $bindings = array(), $useReadPdo = true) { return $this->run($query, $bindings, function($me, $query, $bindings) use ($useReadPdo) { if ($me->pretending()) return array(); // For select statements, we'll simply execute the query and return an array // of the database result set. Each element in the array will be a single // row from the database table, and will either be an array or objects. $statement = $this->getPdoForSelect($useReadPdo)->prepare($query); $statement->execute($me->prepareBindings($bindings)); return $statement->fetchAll($me->getFetchMode()); }); }//commitpublic function commit() { if ($this->transactions == 1) $this->pdo->commit(); --$this->transactions; $this->fireConnectionEvent('committed'); }

三、对比

四、总结

五、参考文献