简体   繁体   English

如何使用php在一行中从mysql查询中获取单个字段?

[英]How do I fetch a single field from a mysql query in one line with php?

php and mysql... PHP和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. 您需要使用fetch_object()因为PHP允许您将->运算符直接链接到函数的返回值上,而使用[ ]运算符则不能。

$keyterm = $result->fetch_object()->keyterm;

Or, procedural style: 或者,程序样式:

$keyterm = mysqli_fetch_object($result)->keyterm;

extract() ( take care ): extract()注意 ):

extract(mysqli_fetch_assoc($result));

You will get a warning when mysqli_fetch_assoc() returns FALSE (non-array). mysqli_fetch_assoc()返回FALSE(非数组)时,您将得到警告。 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. 从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. 那是这里最便宜的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM