从mysql拆分内爆数组到php中的变量

时间:2012-07-24 14:15:44

标签: php mysql arrays explode implode

好吧基本上我无法弄清楚如何将mysql的内爆结果恢复到php中的可用变量。阵列让我陷入困境,让我疯狂。

从db:

动态创建的复选框
<input name="tournament_id[]" value="'.$row['tournament_id'].'" type="checkbox">'.$row['tournament_name'].'

发布的内容被破坏(尚未实施sql注入预防):

$got_tournament_id = implode(",",$_POST['tournament_id']);

这会像这样插入到mysql中:

id   user_id   tournament_id
1    16942627  1,10

这是我的mysql查询来获取内爆数据:

$query = ("SELECT tournament_id FROM tournament WHERE user_id=16942627");
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$got_it = $row['tournament_id'];    
}
$bust_him = var_dump(explode(",", $got_it));
echo $bust_him;

以上使用var_dump返回以下内容:

array(2) { [0]=> string(1) "1" [1]=> string(2) "10" }

现在这是我完全迷失的地方,并且无法弄清楚如何将数组中的值1和10转换为单个变量。我已经尝试了几种方法来做到这一点,并且我总是以错误结束,或者只是单词数组。如果有人可以提供一些,我需要一些帮助。提前谢谢。

1 个答案:

答案 0 :(得分:7)

不要var_dump(),其目的是调试,而不是代码或显示逻辑。只需将explode()的输出存储到$bust_him一个奇怪的变量名称):

// Store the output of explode() directly
$bust_him = explode(",", $got_it);
// No need for individual variables, just access via array keys.
echo $bust_him[0];
echo $bust_him[1];
// etc...

如果您有固定数量的元素,则可以使用list()放入变量:

// You know you only have two, so you can use list()
// to store directly into variables
list($first, $second) = explode(",", $got_it);
echo $first;
echo $second;

从长远来看,比在表中存储以逗号分隔的值更好的解决方案是创建一个单独的,正确规范化的表,该表将tournament_id链接到user_id。然后,每个user_id有多行,每行包含一个 tournament_id。这样可以在很多实例中进行更简单,更有效的查询,例如,可以使用COUNT()聚合,以及许多其他好处。