0

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  | [email protected]  | password  | other
-------------------------------------------------------
example2 | [email protected] | 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("[email protected]", "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?

3
  • 1
    Wrap off quotes form column name!! Commented Apr 11, 2016 at 13:13
  • Because you're asking MySQL to return the text 'NAME' by surrounding it in single quotes, field names should be surrounded with back ticks or nothing at all so mysql understand you want a field value instead of the given text. Commented Apr 11, 2016 at 13:14
  • OH, sorry for this syntax problem. :( Commented Apr 11, 2016 at 13:15

2 Answers 2

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("[email protected]", "name", $connection);
Sign up to request clarification or add additional context in comments.

Comments

0

No quotes around $field.

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

2 Comments

Yeah, it works. Thank you! (sorry for the stupid question i think)
@paolobasso Please prepare your statements, don't just select an email which the user can alter, this is highly vulnerable for SQL injection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.