【发布时间】:2016-12-16 09:55:50
【问题描述】:
我有一个使用 Yii2 框架的项目开发,在我的项目中,我将一个数组发送到 sql 中的单个列中,这是发送到 Sql 之前的以下 数组:
Array(
[0] => Array
(
[0] => Array
(
[0] => first_name
[1] => last_name
[2] => age
[3] => sex
)
)
[1] => Array
(
[0] => Array
(
[0] => Andrew
[1] => Lugiano
[2] => 18
[3] => Male
)
)
[2] => Array
(
[0] => Array
(
[0] => Elizabeth
[1] => Natari
[2] => 21
[3] => Female
)
)
)
这是我的 CustomHeaderController 中的代码:
$encoded_array = json_encode($arrayData);
$command_2 = "INSERT INTO data(array_data) VALUES('$encoded_array')";
$query_2 = Yii::$app->db->createCommand($command_2)->execute();
Sql中的列名为array_data,数据类型为mediumtext,表名为data。
然后我尝试通过 SaveController 从 sql 中取回它,这是我用来从 Sql 中获取数据的代码:
$sql = $connection->createCommand("SELECT array_data FROM data WHERE user_id=$userId");
$modelHeader = $sql->queryColumn();
但我得到了这个结果:
数组 ( [0] => [[["first_name",''last_name'',''age'', "sex"]],[["Andrew","Lugiano","18","Male"]], [[“伊丽莎白”,“娜塔莉”,“21”,“女”]]] )
这不是我的预期结果,这是我的项目所需要的(就像发送到 Sql 之前一样)
数组 ( [0] => 数组 ( [0] => 数组 ( [0] => 名字 [1] => 姓氏 [2] => 年龄 [3] => 性别 ) ) [1] => 数组 ( [0] => 数组 ( [0] => 安德鲁 [1] => 卢吉亚诺 [2] => 18 [3] => 男 ) ) [2] => 数组 ( [0] => 数组 ( [0] => 伊丽莎白 [1] => 纳塔利 [2] => 21 [3] => 女性 ) ) )
如何从 Sql 中获取数据,就像我的预期结果一样?
【问题讨论】:
-
你忘记
json_decode查询结果了…… -
它不能
json_decode,因为$sql->queryColumn();代码将结果直接设置为数组。也许你知道我怎样才能得到一个字符串的结果,所以我可以json_decode它? @deceze -
我可以知道为什么我被否决了吗?谢谢
-
queryColumn返回一个列数组。该数组中的第一个条目是您放入数据库的 JSON 字符串。所以……json_decode($modelHeader[0]). -
有一个 google 用于 sql 注入