如何将查询结果中的值转换为变量和变量值?
问题描述:
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. Like this:
column1 | column2
value1 | value2
value3 | value4
The result should be:
$value1 = "value2"
$value3 = "value4"
etc..
Is there any way to achieve this with one singe query?
我正在尝试从数据库中提取两列,并将column1值转换为变量名称和值 column2进入变量值。 如下: p>
column1 | column2 p>
value1 | value2 p>
value3 | value4 p>
结果应为:
$ value1 =“value2”
$ value3 =“value4”
etc ..
code> pre>
有没有办法用一个单一的查询来实现这个目标? p>
div>
答
You can achieve it by php code,
$query = "SELECT col1, col2 FROM test";
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);