php – 防止无限制的mysqli查询
发布时间:2020-12-13 22:25:14 所属栏目:PHP教程 来源:网络整理
导读:我在一家使用 this Mysqli php class to do mysql calls的公司工作. 问题是,以前的程序员在防止无限查询方面并不出色.所以有些东西分散在整个代码中,如下所示: $db - where('id',$_POST['id']);$db - delete('table'); 此代码应该只删除一个id = $_POST [‘
我在一家使用
this Mysqli php class to do mysql calls的公司工作.
问题是,以前的程序员在防止无限查询方面并不出色.所以有些东西分散在整个代码中,如下所示: $db -> where('id',$_POST['id']); $db -> delete('table'); 此代码应该只删除一个id = $_POST [‘id’]的记录.但是,如果$_POST [‘id’]为空,我们就遇到了问题.然后它删除整个表.解决此问题的一个方法是找到代码中调用delete或update函数的所有位置,然后确保实际设置了where变量. if(isset($_POST['id']) && $_POST['id']!=''){ $db -> where('id',$_POST['id']); $db -> delete('table'); } 但是,这需要很多工作,因为我知道代码中有大约200个实例.我希望可能有一种方法可以改变以下两个函数,以防止它们首先执行未绑定的查询.任何帮助表示赞赏!! /** * Update query. Be sure to first call the "where" method. * * @param string $tableName The name of the database table to work with. * @param array $tableData Array of data to update the desired row. * * @return boolean */ public function update($tableName,$tableData) { if ($this->isSubQuery) return; $this->_query = "UPDATE " . self::$_prefix . $tableName ." SET "; $stmt = $this->_buildQuery (null,$tableData); $status = $stmt->execute(); $this->reset(); $this->_stmtError = $stmt->error; $this->count = $stmt->affected_rows; return $status; } /** * Delete query. Call the "where" method first. * * @param string $tableName The name of the database table to work with. * @param integer $numRows The number of rows to delete. * * @return boolean Indicates success. 0 or 1. */ public function delete($tableName,$numRows = null) { if ($this->isSubQuery) return; $this->_query = "DELETE FROM " . self::$_prefix . $tableName; $stmt = $this->_buildQuery($numRows); $stmt->execute(); $this->_stmtError = $stmt->error; $this->reset(); return ($stmt->affected_rows > 0); } public function where($whereProp,$whereValue = 'DBNULL',$operator = '=',$cond = 'AND') { // forkaround for an old operation api if (is_array($whereValue) && ($key = key($whereValue)) != "0") { $operator = $key; $whereValue = $whereValue[$key]; } if (count($this->_where) == 0) { $cond = ''; } $this->_where[] = array($cond,$whereProp,$operator,$whereValue); return $this; } 解决方法
当它被传递给where函数时,你应该捕获坏值,而不是以后.这样,跟踪堆栈跟踪就更容易了.
public function where($whereProp,$cond = 'AND') { if (is_null($whereValue) || trim($whereValue) == '') { throw new Exception('Cannot pass null or empty string as a condition to MysqliDb::where') } // ... } 您也可以通过delete函数内部的_where protected属性数组进行检查,但是通过简单地返回函数来静默地使方法失败并不是一个好习惯.如果你坚持,但是: public function delete($tableName,$numRows = null) { foreach ($this->_where as $w) { if (is_null($w[3]) || trim($w[3]) == '') { return; // or alternatively throw new Exception('...') } } // ... } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |