简体   繁体   English

如果陈述依赖于SQL查询结果,如何制作PHP

[英]How to make a PHP if statment dependent on SQL query results

I am trying to echo out the user level depending on whether the user level is either 1 or 5 based on SQL data results. 我试图根据SQL数据结果根据用户级别是1还是5来回显用户级别。 Here: 这里:

<?php while ($rrows = mysql_fetch_array($rs_results)) {?>
      <tr> 
        <td><input name="u[]" type="checkbox" value="<?php echo $rrows['id']; ?>"     id="u[]"></td>
        <td><?php echo $rrows['id']; ?></td>
        <td><?php echo $rrows['date']; ?></td>
        <td><?php echo $rrows['user_name'];?></td>
        <td><?php echo $rrows['user_email']; ?></td>
        <td><?php ?></td>

So I need a sort of if statement to select the user level from $rrows['id'] then if that selected data is 1 echo out "Network" and if it is "5" echo out "Administrator". 因此,我需要一种if语句来从$rrows['id']选择用户级别,然后如果所选数据为1,则回显“网络”,如果为5,则回显“管理员”。 How can this be done? 如何才能做到这一点?

Seems like you need something like that: 似乎您需要这样的东西:

$user_levels = array('Network','role2','role3','role4','Administrator');

<?php while ($rrows = mysql_fetch_array($rs_results)) {?>
      <tr> 
        <td><input name="u[]" type="checkbox" value="<?php echo $rrows['id']; ?>"     id="u[]"></td>
        <td><?php echo $rrows['id']; ?></td>
        <td><?php echo $rrows['date']; ?></td>           
        <td><?php echo $users_levels[(int)$rrows['id']-1]; ?></td>
        <td><?php echo $rrows['user_name'];?></td>
        <td><?php echo $rrows['user_email']; ?></td>
        <td><?php ?></td>

The reason I am using -1 in the array is because the array is 0 based and your roles start with 1. If you need to use the 'user_level' simply replace the row with 我在数组中使用-1的原因是因为数组基于0,并且您的角色以1开头。如果您需要使用“ user_level”,只需将行替换为

<td><?php echo $users_levels[(int)$rrows['user_level']-1]; ?></td>

Hope this helps! 希望这可以帮助!

I wouldn't do it with a if statement. 我不会用if语句来做。 I'd do it like that: 我会那样做:

$levels = array(1 => "Network", 5 => "Administrator");
echo $levels[$rrows['user_level']];

That way, if you want to add other levels, you just add a value to the array and that's it. 这样,如果您想添加其他级别,只需在数组中添加一个值即可。

I wonder how you got that far without an if statement but anyway, you also could do this right in you sql query. 我不知道您如何在没有if语句的情况下实现这一目标,但是无论如何,您也可以在sql查询中做到这一点。 I always try to outsource as much logic to mysql as possible for a balanced load distribution. 我总是尝试将尽可能多的逻辑外包给mysql,以实现均衡的负载分配。

SELECT level, IF(level = 1, 'Network', 'Administrator') as level FROM table

I think you can nest if statements to have more options. 我认为您可以嵌套if语句以具有更多选项。

Adapted from this answer: 'IF' in 'SELECT' statement - choose output value based on column values 根据以下答案改编: 'SELECT'语句中的'IF'-根据列值选择输出值

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

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