我有一个看起来像这样的SQL表
--------------------------------- | id | di | field | content | --------------------------------- | 1 | kh | dvh | lorem ips | --------------------------------- | 2 | kh | kkf | hor ameti | --------------------------------- | 3 | db | hgd | usyytutt | ---------------------------------
我想要的是从sql中选择并返回field
成为列名的变量的方法;像这样:
$sql = $conn->prepare('SELECT * FROM table WHERE `di` = "kh"'); // And some more fancy code $sql = execute(); $row = $sql->fetch(PDO::FETCH_ASSOC); echo $row['dvh']; // outputs 'lorem ips'
目前我使用php来转换返回的数组:
$result = $sql->fetchAll(PDO::FETCH_ASSOC);
然后通过foreach循环运行它们:
$data = array(); foreach ($result as $k => $val) { $data[$val['field']] = $data['content']; }
我真的希望SQL为我做这件事。