简体   繁体   English

如何将查询结果中的值转换为变量和变量值?

[英]How to turn values from a query result into variable and variable value?

I'm trying to pull two columns from my database and turn the column1 value into the variable name and the value from column2 into the variable value. 我正在尝试从数据库中提取两列,并将column1的值转换为变量名,将column2的值转换为变量值。 Like this: 像这样:

column1 | 第1列| column2 COLUMN2

value1 | value1 | value2 值2

value3 | value3 | value4 VALUE4

The result should be: 
$value1 = "value2"
$value3 = "value4"
etc..

Is there any way to achieve this with one singe query? 有什么办法可以通过一个单一查询实现此目的?

You can achieve it by php code, 您可以通过php代码来实现,

$query = "SELECT col1, col2 FROM test"; $ query =“ SELECT col1,col2 FROM测试”;

if($result = mysqli_query($conn, $query)) { if($ result = mysqli_query($ conn,$ query)){

/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
    ${$row['col1']} = $row['col2'];
}

echo $val1;     // Echos val2
echo "<br />";
echo $val3;     // Echos val4
/* free result set */
mysqli_free_result($result);

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

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