gpt4 book ai didi

php - 防止无限的 mysqli 查询

转载 作者:可可西里 更新时间:2023-10-31 23:46:20 24 4
gpt4 key购买 nike

我在一家使用 this Mysqli php class to do mysql calls 的公司工作.问题是,以前的程序员不太擅长防止无限查询。所以有些东西分散在整个代码中,如下所示:

$db -> where('id',$_POST['id']);
$db -> delete('table');

此代码应该只删除一条记录,其中 id = $_POST['id']。但是,如果 $_POST['id'] 为空,我们就会遇到问题。然后它删除整个表。此问题的一种解决方案是找到代码中调用删除或更新函数的所有位置,然后确保实际设置了 where 变量。

if(isset($_POST['id']) && $_POST['id']!=''){
$db -> where('id',$_POST['id']);
$db -> delete('table');
}

但是,这需要大量工作,因为我知道代码中大约有 200 个实例。我希望可能有一种方法可以改变以下 2 个函数,以防止它们首先执行未绑定(bind)的查询。感谢您的帮助!!

/**
* 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, $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')
}
// ...
}

您也可以检查 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('...')
}
}
// ...
}

关于php - 防止无限的 mysqli 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34864453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com