0

Say I have an array which fetched a single row from my database via the PDO::FETCH_ASSOC method, which I would then assign to a variable like so:

$result = $stmt->fetch(PDO::FETCH_ASSOC);

$result now holds an array equal to the following:

Array ( 
  [id] => 42
)

So, to assign the value 'id' to a variable by itself, I then have to go:

$id = $result['id'];

Is there a quicker way to do this, or even better, to make sure the query result from my database is a variable rather than an array directly, assuming the query is always guaranteed to return 1 result?

1

2 Answers 2

1

This should do the trick

$result = $stmt->fetchColumn();

Docs here (just noticed Mark Baker also put it in his comment).

Sign up to request clarification or add additional context in comments.

Comments

1

in PHP >= 5.4, try

$result = $stmt->fetch(PDO::FETCH_ASSOC)[0];

this is a guess, though, you have to test it.

Comments

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.