Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to return a single database result?

Tags:

php

mysql

All I want to do is get the firstname result from this function, but it feels it's too much code to do that based on session 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?
like image 592
Drew Peer Avatar asked Dec 30 '25 18:12

Drew Peer


1 Answers

To do this properly using prepared statements you actually need more code than that:

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];
}

I'm not sure what confirm_result_set is so I left it out.

Let's pretend that $db was a PDO object:

function find_name_by_id($db, $id) {
    $stmt = $db->prepare("SELECT firstname FROM admins WHERE id=?");
    $stmt->execute([$id]);
    return $stmt->fetchColumn();
}

Much less code involved. And for a higher-level API this will be abstracted to a single line of code.

In reality for all cases you'd want to do some error checking, account for no records being returned, etc. Also you should avoid global variables, they're very poor form. Put your code into a class or just use dependency injection as I've done.

like image 76
miken32 Avatar answered Jan 01 '26 07:01

miken32



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!