繁体   English   中英

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

[英]Splitting imploded array from mysql to variables in php

好吧基本上我无法弄清楚如何将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转换为单个变量。 我已经尝试了几种方法来做到这一点,并且我总是以错误结束,或者只是单词数组。 如果有人可以提供一些,我需要一些帮助。 提前致谢。

不要使用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()聚合,以及许多其他好处。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM