首页 > 解决方案 > 返回单个数据库结果的正确方法是什么?

问题描述

我想要做的就是从这个函数中获取名字结果,但是感觉基于会话 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?

标签: phpmysql

解决方案


要使用准备好的语句正确执行此操作,您实际上需要更多代码:

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,这将被抽象为一行代码。

实际上,对于所有情况,您都希望进行一些错误检查,考虑不返回任何记录等。此外,您应该避免使用全局变量,它们的形式非常糟糕。将您的代码放入一个类中,或者像我一样使用依赖注入。


推荐阅读