在看书时,我遇到了以下函数:
/*
Update records in the database
@param String $table the table being updated
@param Array $changes array of changes field => value
@param String $condition the condition
@return Boolean
*/
public function updateRecords($table, array $changes, $condition)
{
$update = "UPDATE " . $table . " SET ";
foreach($changes as $field => $value)
{
$update .= "`" . $field . "` = '{$value}', ";
}
//remove trailing , (comma)
$update .= substr($update, 0, -1);
if($condition != '')
{
$update .= "WHERE " . $condition;
}
$this->executeQuery($update);
//Not sure why it returns true.
return true;
}
如果我错了,请纠正我,但这不是一个设计糟糕的函数,完全没有数据过滤/检查。大多数函数总是返回true。
正确。它似乎是在通过字符串串联构建SQL语句,而不执行任何环境清理。如果所有输入都是可信的,那么这个可能是可以接受的,但考虑到它是public
函数,我认为情况并非如此。
return true
似乎是多余的,因为它从不返回任何其他内容——作者可能打算将其作为确保函数完成的一种方式,这意味着它使用的代码会无声地失败,而不是调用die()
或抛出异常。
就风格而言,作者与串联并不一致:在某些地方,它是使用.
运算符的直接串联,而在其他地方,它使用$placeholders
。
如果$changes
为空,那么对substr
的调用将失败,在构建列表后进行修剪是逗号分隔列表项的错误方法。我就是这样做的(当然,除了SQL):
$first = true;
foreach($changes as $field => $value ) {
if( !$first ) $update .= ", ";
$first = false;
$update .= "`$field` = '{$value}'"; // NEVER DO THIS
}
仔细想想,这个函数唯一好的地方就是它有很好的文档记录。