PHP function to extract a field value from a database

强颜欢笑 提交于 2020-01-07 01:59:33

问题


I'm trying to get a value of a mysql database using a php function. I have a database like this:

NAME     | EMAIL                | PASSWORD  | OTHER
-------------------------------------------------------
example  | example@example.com  | password  | other
-------------------------------------------------------
example2 | example2@example.com | password2 | other2

and in my PHP file I've tried to use this function:

function selectUserField($email, $field, $connection){
    $select_user = "SELECT '$field' FROM users WHERE email='$email' LIMIT 1";
    $result = mysqli_query($connection, $select_user);
    $value = mysqli_fetch_assoc($result);
    return $value[$field];
}

//And I try to echo the result of the function
$connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

echo selectUserField("example@example.com", "name", $connection);

But as result I get only the field name and not its content (for this example I get "NAME" and not "example"). How can i do to get the content of the database cell?


回答1:


No quotes around $field.

"SELECT $field FROM users WHERE email='$email' LIMIT 1";



回答2:


Try this

function selectUserField($email, $field, $connection){
    $select_user = "SELECT `$field` FROM users WHERE `email`='$email' LIMIT 1"; //wrap it with ` around the field or don't wrap with anything at all
    $result = mysqli_query($connection, $select_user);
    $value = mysqli_fetch_assoc($result);
    return $value[$field];
}

//And I try to echo the result of the function
$connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

echo selectUserField("example@example.com", "name", $connection);


来源:https://stackoverflow.com/questions/36549728/php-function-to-extract-a-field-value-from-a-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!