php - 返回单个数据库结果的正确方法是什么?
问题描述
我想要做的就是从这个函数中获取名字结果,但是感觉基于会话 ID 来做这件事的代码太多了。
//query_functions.php
function find_name_by_id($id) {
global $db;
$sql = "SELECT firstname FROM admins ";
$sql .= "WHERE id='" . db_escape($db, $id) . "' ";
$sql .= "LIMIT 1";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
$name = mysqli_fetch_assoc($result); // find first
mysqli_free_result($result);
return $name; // returns an assoc. array
}
// admin.php
id = $_SESSION['admin_id'];
$name = find_name_by_id($id);
// what is the shortest way to get this $name result?
解决方案
要使用准备好的语句正确执行此操作,您实际上需要更多代码:
function find_name_by_id($db, $id) {
$stmt = $db->prepare("SELECT firstname FROM admins WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$stmt->free_result();
return $row[0];
}
我不确定是什么confirm_result_set
所以我把它排除在外。
让我们假设这$db
是一个 PDO 对象:
function find_name_by_id($db, $id) {
$stmt = $db->prepare("SELECT firstname FROM admins WHERE id=?");
$stmt->execute([$id]);
return $stmt->fetchColumn();
}
涉及的代码少得多。对于更高级别的 API,这将被抽象为一行代码。
实际上,对于所有情况,您都希望进行一些错误检查,考虑不返回任何记录等。此外,您应该避免使用全局变量,它们的形式非常糟糕。将您的代码放入一个类中,或者像我一样使用依赖注入。
推荐阅读
- x86-64 - x86_64 架构是否在不断更新?
- javascript - Firestore 数据库不会出现
- api - 在 QGIS 'Hqgis' 插件中使用 HERE API 循环路由。可以做到吗?
- woocommerce - 仅针对特定条款在函数内运行税务查询(WooCommerce)
- delphi - 是否可以对属性使用相同的 getter 和 setter?
- outlook - 从 Outlook 主题行中提取文本
- sql - SQL 根据 ParentID 和 Child ID 对数据进行分组
- xslt - 在一个查询中使用 sum 翻译函数
- javascript - 访问在对象中分配为常量的对象数组并映射其值
- java - Java 嵌套类