我在使用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;
}
答案 0 :(得分:0)
如果这个(where子句)为空,那么返回怎么办?
https://docs.mongodb.org/manual/reference/method/WriteResult/#WriteResult
if (count($this->_where) == 0) {
return;
}
答案 1 :(得分:0)
当它传递给where
函数时,你应该捕获坏值,而不是以后。这样就可以更容易地跟踪堆栈跟踪。
public function where($whereProp, $whereValue = 'DBNULL', $operator = '=', $cond = 'AND')
{
if (is_null($whereValue) || trim($whereValue) == '') {
throw new Exception('Cannot pass null or empty string as a condition to MysqliDb::where')
}
// ...
}
您也可以通过_where
函数内部的delete
受保护属性数组进行检查,但是通过从函数中执行简单的return
来静默地使方法失败并不是一种好习惯。如果你坚持,但是:
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('...')
}
}
// ...
}
答案 2 :(得分:0)
请更新到最新的稳定版本。这个问题在那里得到解决。
其中(' val',未设置)不会被视为无条件。