return one value from database with mysql php pdo

You can use fetchColumn():

$q= $conn->prepare("SELECT name FROM `login_users` WHERE username=?");
$q->execute([$userid]);
$username = $q->fetchColumn();

Just like it's far too much work to have to get into your car, drive to the store, fight your way through the crowds, grab that jug of milk you need, then fight your way back home, just so you can have a milkshake.

All of those stages are necessary, and each subsequent step depends on the previous ones having been performed.

If you do this repeatedly, then by all means wrap a function around it so you can reuse it and reduce it down to a single getMyValue() call - but in the background all that code still must be present.


You could create a function for this and call that function each time you need a single value. For security reasons, avoid concatenating strings to form an SQL query. Instead, use prepared statements for the values and hardcode everything else in the SQL string. In order to get a certain column, just explicitly list it in your query. a fetchColumn() method also comes in handy for fetching a single value from the query

function getSingleValue($conn, $sql, $parameters)
{
    $q = $conn->prepare($sql);
    $q->execute($parameters);
    return $q->fetchColumn();
}

Then you can simply do:

$name = getSingleValue($conn, "SELECT name FROM login_users WHERE id=?", [$userid]); 

and it will get you the desired value.

So you need to create that function just once, but can reuse it for different queries.

This answer has been community edited addressing security concerns

Tags:

Mysql

Php

Pdo