使用函数查询mysql需要更多时间加载?

问题描述:

I was wondering if using function to query specific row from a table each time the function is being called will be less sufficient than just querying once by a normal mysql query.

here's a clearer picture of what I mean.

function userinfo($table, $row, $data, $where){
global $db;
$users_sql = $db->query("SELECT $row FROM $table WHERE $where = '$data'");
$users_row = $db->fetch_assoc($users_sql);
return $users_row[$row];
}

echo userinfo('users', 'firstname', $_SESSION['username'],'username');
echo userinfo('users', 'avatar', $_SESSION['username'],'username');

or just doing this without a function

$users_sql = $db->query("SELECT $row FROM $table WHERE $where = '$data'");
$users_row = $db->fetch_assoc($users_sql);
echo $users_row['firstname'];
echo $users_row['avatar'];

I'm guessing the second way will be better, but I just gotta double check.

Change the first to:

function userinfo($table, $row, $data, $where){
    global $db;
    $users_sql = $db->query("SELECT $row FROM $table WHERE $where = '$data'");
    $users_row = $db->fetch_assoc($users_sql);
    return $users_row;
}
$row = userinfo('users', 'firstname, avatar', $_SESSION['username'],'username');
echo $row['firstname'];
echo $row['avatar'];

will make it more meaningful and avoid an additional database query; but your second "without a function" equivalent isn't equivalent at all because you're assuming that $users_row will return both firstname and avatar, while your first example doesn't (unless you use the logic I've shown above)

Even more generic would be

function userinfo($table, $data, $where){
    global $db;
    $users_sql = $db->query("SELECT * FROM $table WHERE $where = '$data'");
    $users_row = $db->fetch_assoc($users_sql);
    return $users_row;
}
$row = userinfo('users', $_SESSION['username'],'username');
echo $row['firstname'];
echo $row['avatar'];

But your approach to this isn't good; you really should be using prepared statements and bind variables; and building your queries accordingly