3

I am new to PHP and have a really basic question.

If I know the result of a query is only a single value (cell) from a single row in MySQL how can I simplify the below without having to go through an array of results and without increasing the risk of SQL injection ?

In the example below I would just need to echo a single email as the result of the query.

I found a couple of posts suggesting different approaches with fetch_field for this but I am not sure what is the best way here since some of these seem to be pretty old or deprecated now.

My PHP:

$stmt = $conn->prepare("SELECT email FROM Users WHERE userName = ? LIMIT 1");
$stmt->bind_param('s', $userName);
$stmt->execute();
$result = $stmt->get_result();
$arr = $result->fetch_assoc();
echo $arr["email"];

Many thanks in advance.

1 Answer 1

5

You can avoid caring what the column is called by just doing this:

<?php
$stmt = $conn->prepare("SELECT email FROM Users WHERE userName = ? LIMIT 1");
$stmt->bind_param('s', $userName);
$stmt->execute();

$email = $stmt->get_result()->fetch_object()->email;
echo $email;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this. Does the result always have to be an array here ? I thought instead of fetch() I could use something like fetch_field so that the result is already just a single value instead of an array.
No problem. Ah, I see. Check out my edit above; this might be a good solution. fetch_object() returns an object with the field names as properties, so it can be dereferenced via -> to get just the email field here.

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.