How do I fetch a single field from a mysql query in one line with php?
php and mysql...
the query:
$sql = "SELECT keyterm
FROM 开发者_如何学编程keyterms
WHERE keyterm_id = $keyterm_id";
$result = mysqli_query($dbcon,$sql); // returns a single result
fetch results:
$keyterm = mysqli_fetch_assoc($result);
$keyterm = $keyterm["keyterm"];
what is the equivalent of the last two lines in a single line?
You need to use fetch_object()
because PHP allows you to chain the ->
operator directly onto the return value of a function, which you cannot do with the [ ]
operator.
$keyterm = $result->fetch_object()->keyterm;
Or, procedural style:
$keyterm = mysqli_fetch_object($result)->keyterm;
extract()
(take care):
extract(mysqli_fetch_assoc($result));
You will get a warning when mysqli_fetch_assoc()
returns FALSE (non-array). Field/Column name must be named as the variable.
Edit: Made it bold as some might have not read that.
If you only fetch a single column, you can also use:
$keyterm = current(mysql_fetch_array($result));
Works since PHP5. It just gets the first entry from the array (whether indexed or associative), and assigns it to the variable. That's the cheapest option here.
精彩评论