我最近开始使用 MySQLi 准备好的语句。我不喜欢仅仅一个简单的选择语句就需要多少行代码。所以我创建了一个包装函数,请参阅下面问题下面的代码。 注意:get_results() 或 PDO 不适合我。
我的问题是:
它会显着降低性能吗?
会不会因为使用result数组而占用更多内存?
- 返回前的$stmt->close()会不会有问题?例如,结果数组数据是否也已从内存中释放?
- 我是否需要关闭或释放其他任何东西(关闭数据库连接除外)?
- 您是否发现该功能有任何其他问题或是否可以改进?
代码:
class DatabaseHelper{
static function select($con, $query, $formats, $params){
$a_params = array();
$param_type = '';
$n = count($formats);
for($i = 0; $i < $n; $i++) {
$param_type .= $formats[$i];
}
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
$a_params[] = & $params[$i];
}
$stmt = $con->prepare($query);
call_user_func_array(array($stmt, 'bind_param'), $a_params);
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$columns[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $columns);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
$stmt->close();
return $results;
}
}
例如这样使用:
$users = DatabaseHelper::select($conn, "SELECT name,username FROM users WHERE id > ?", "i", array(30));
foreach ($users as $row){
echo $row['username'] . " ". $row['name'] . "<br />";
}
最佳答案
Will it slow down the performance noticeably?
没有。
Will it be more memory intensive because of the use of the result array?
不需要,只要您选择的数据量合理。在现代应用程序中,您必须首先选择所有数据,因为业务逻辑应该与显示逻辑分开。
Will the $stmt->close() before the return cause any problems? For example maybe the result array data is also are freed from memory?
为什么不试试看呢?
Do I need to close or free anything else (except from closing the db connection)?
您也不必关闭语句。
Do you see any other problems with the function or could it be improved?
- 首先也是最重要的。由于它是您正在编写的类,而不是函数,因此通过参数传递连接绝对没有意义。使其成为静态属性。
- 此外,我建议将类型设置为具有默认值的最后一个参数。在大多数情况下,您不必对类型挑剔 - 默认字符串即可。
- 此外,由于您的 PHP 版本是 5.6,您可以使用 splat 运算符来减少代码量。你可以查看this answer of mine了解详情
- 我还建议将您的函数拆分为多个方法 - 一个用于执行查询,其他用于获取结果。它可以让您为各种查询重复使用相同的代码
- 确保你是watching for mysqli errors as explained here
因此,理想情况下,您会以这种方式调用您的查询
$users = DatabaseHelper::getAll("SELECT name,username FROM users WHERE id > ?", [30]);
foreach ($users as $row){
echo $row['username'] . " ". $row['name'] . "<br />";
}
其中 getAll() 方法在内部使用 query() 方法执行查询,然后获取所有结果。同样,您可能想编写 getRow() 和 getOne() 方法
关于php - MySQLi 准备好的语句 - SELECT 的包装函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41281404/