简体   繁体   English

PHP MySQL 函数统计输出

[英]PHP MySQL function counts output

I wrote a function in which a value for a button should be fetched from two tables.我编写了一个函数,其中应该从两个表中获取按钮的值。 Five buttons should be displayed side by side.五个按钮应并排显示。 This works theoretically, but the output is displayed 5 times for the first button, 4 times for the second button, etc.这在理论上是有效的,但是第一个按钮的输出显示 5 次,第二个按钮显示 4 次,依此类推。

What am I missing that the output is output multiple times?我错过了多次输出输出的内容吗?

function get_strat($map_id, $map_site, $operator_role_input) {

    global $connection;

    $query = "SELECT * FROM strat WHERE map_id = $map_id AND strat_role_id = $map_site";
    $select_all_defense_strats = mysqli_query($connection, $query);

    while($row = mysqli_fetch_assoc($select_all_defense_strats)) {

        $map_id = $row['map_id'];
        $operator_id = $row['operator_id'];
        $operator_role = $row['operator_role'];

        if($operator_role === $operator_role_input) {
            $query = "SELECT operator_name FROM operator WHERE operator_id = $operator_id";
            $get_operator_name = mysqli_query($connection, $query);

            $row = mysqli_fetch_assoc($get_operator_name);

            $operator_name = $row['operator_name'];

        } 

        echo $operator_name;

    }
}
<div class="btn-group">
    <button type="button" class="btn btn-default">
        <?php 
            $operator_role_input = '1';
            get_strat($map_id, $map_site, $operator_role_input);
        ?>
    </button>
    <button type="button" class="btn btn-default">
        <?php 
            $operator_role_input = '2';
            get_strat($map_id, $map_site, $operator_role_input);
                    ?>
    </button>
    .... (up to 5)

实际产量

Because your variable $operator_name is outside of if statement .因为您的变量$operator_nameif statement之外。 When it has value - it prints it.当它有价值时 - 它会打印它。 When comparing is false - then it's undefined .当比较为假时 - 那么它是undefined

Put default value of it before if statement :将它的默认值放在if statement之前:

$operator_name = '';
if(){...}
echo $operator_name;

Or just put your echo $operator_name;或者只是把你的echo $operator_name; inside and in the end of your if statement .if statement内部和结尾。

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

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