php mysql如何在fetch\u assoc之后将列/字段名设置为变量

ehxuflar  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(392)

我正在尝试获取列名和值,然后将列名设置为变量。。。有道理吗?

$con = mysqli_connect('localhost', 'mysql_user', 'mysql_password', 'db_name');
$sql = "SELECT * FROM `table`";
$res = mysqli_query($con,$sql);
while($row = $res->fetch_assoc()) {
    $column1 = $row['column1']; // <- can these be
    $column2 = $row['column2']; // as simple as one
    ...
    $column100 = $row['column100']; // line or two?
}
mysqli_close($con);

有人能指导我怎么做吗?谢谢。

cclgggtu

cclgggtu1#

可以使用字符串来声明变量,称为variable variables

while($row = $res->fetch_assoc()) {
    foreach ($row as $key => $value)
        $$key = $value;
//      ^----------------------notice the double dollar
}

或者,你可以用提取物

while($row = $res->fetch_assoc()) {
    extract($row);
}

为了确保您不想覆盖一些已经存在的变量,您可以给它们加前缀。

while($row = $res->fetch_assoc()) {
    foreach ($row as $key => $value)
        $someNicePrefix_{$key} = $value;
//                      ^----^-------------notice the curly brackets
}

使用extract,可以添加更多参数(在上面链接的文档中描述)

while($row = $res->fetch_assoc()) {
    extract($row, EXTR_PREFIX_ALL, "someNicePrefix");
}

两种方法的效果相同。注意,对于extract,一个字符 _ 将插入前缀和变量名之间

相关问题