【问题标题】:Splitting imploded array from mysql to variables in php将内爆数组从mysql拆分为php中的变量
【发布时间】:2012-07-22 21:15:44
【问题描述】:

好吧,基本上我不知道如何将 mysql 的内爆结果返回到 php 中的可用变量。数组让我陷入循环,让我发疯。

从数据库动态创建的复选框:

<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 从数组中获取到单个变量中。我尝试了几种方法来做到这一点,但我一直以错误告终,或者只是单词数组。如果有人可以提供一些帮助,我需要一些帮助。提前致谢。

【问题讨论】:

    标签: php mysql arrays explode implode


    【解决方案1】:

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

    【讨论】:

    • 感谢您指出正确的方向。我一直在回答只是不太正确,但再次感谢您。我还考虑过重做我所拥有的,并实施你提到的关于规范化表的内容,因为我认为从长远来看这会更好。再次感谢您的快速回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2011-01-11
    相关资源
    最近更新 更多