【问题标题】:Retrieve data from array从数组中检索数据
【发布时间】:2014-03-16 10:12:44
【问题描述】:

我有一个小问题,我的代码存储了值并且可以像往常一样运行,但是当我想再次显示它时,该值不会显示并且错误是:

注意:未定义变量:C:\xampp\htdocs\eAttendance\*******.***php 中第 91 行的 result_c

这是:

<td><?php echo $GLOBALS['result_c'] ?></td>

我的问题是:

  1. 为什么我不能在$result_c 中回调我的变量?
  2. 我该怎么办?你有什么想法吗?
  3. 使此编码成功的适当方法是什么?

我编写此代码是因为我想计算存储在$result_c 中的数组中的所有值,以成为平均出勤率。

<table >
<tr>
 <td>Matrix Card</td>
    <td>Percent</td>
 </tr>
 <?php
$sbj = $_GET['sbj'];
$cls = $_GET['cls'];
  $sql = mysql_query ("SELECT * FROM stu_course where class = '$cls' and subject_code = '$sbj'");
  $a = 0;

  while ($row = mysql_fetch_assoc($sql)){ 
       ?>
      <tr>
          <?php
    $result1[] = $row['login_id'];

    $sql1 = mysql_query("Select * from attendance where id_student = '$result1[$a]' and subject_code = '$sbj'") or die('Query failed. ' . mysql_error());
    $b = 0;
    while($row1 = mysql_fetch_assoc($sql1))
    {
        $popo = 1;
        $result_array[] = $row1['credit_hour'];
        $add = $result_array[$b];
        $result_c = $result_c + $add;
    }?>
      <td><?php echo $result1[$a];?></td>
     <td><?php echo $GLOBALS['result_c'] ?></td>
   <?php             
    $a++;      
  }
  ?>
  </tr>
</table>

【问题讨论】:

  • 该代码有很多错误,您没有初始化 $result_c 变量,您正在使用 $GLOBALS 尽管 $result_c 在您当前而不是全局范围内,但您始终在设置将 $popo 变量设置为 1 而从未使用它(或者如果您删除了那部分代码,那么您可以简单地将变量设置在循环之外。要回到最初的问题,只需使用 $result_c 而不是 $GLOBALS['result_c'] .
  • ……你真的不应该把未转义的 get 参数直接放在你的查询中

标签: php html mysql arrays


【解决方案1】:

为什么不能输出&lt;?php echo $GLOBALS['result_c'] ?&gt; 而不是&lt;?php echo $result_c ?&gt;?还是我理解不正确。

【讨论】:

  • 它仍然不会显示 $result_c .. 但是当我喜欢这样的 sql 查询
    "$sql1 = mysql_query("Select * from admission where id_student = '202133415' and subject_code = 'FP 901'") 或 die('查询失败。' .mysql_error());"
    它将在 $result_c 中显示值存储。我刚刚更改了 sql 查询。也许我不能直接做,需要过滤器使它成为字符串?
  • $sql1 = mysql_query("Select * from attendance where id_student = '$result1[$a]' and subject_code = '$sbj'") or die('Query failed. ' . mysql_error()); 没有返回任何行吗?尝试在字符串中的数组变量周围添加{}。即$sql1 = mysql_query("Select * from attendance where id_student = '{$result1[$a]}' and subject_code = '$sbj'") or die('Query failed. ' . mysql_error());
  • 它将返回一个结果,但结果将是 $result1 中的零 / 0 .... 如果我在 sql 查询语句中更改“ $sql1 = mysql_query("Select * from admission where id_student = '1909dsa' and subject_code = '$sbj'") " .. 它将显示值..
  • 您是否将数组变量包装在{} 中,再看看我之前的评论。
  • 是的,我用 {} 做到了 .. 结果还是一样.. 显示值为 0 .. 为什么?是关于 mysql_real_escape_string
【解决方案2】:

我也会使用准备好的语句。这是一个例子: http://forums.phpfreaks.com/topic/285929-pdo-in-a-php-class/#entry1467894

您似乎将数据直接从客户端注入到您的数据库调用中,从而使您很容易受到攻击!

【讨论】:

    【解决方案3】:

    尝试在 while 循环之外声明 $result_c,这样您就不必使用 $GLOBALS 来处理您遇到的变量范围问题。此外,不建议使用 $GLOBALS。

    额外建议:我建议您使用您的命名约定,以便我们更容易理解您的代码。

    【讨论】:

      猜你喜欢
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2015-03-02
      • 2018-12-15
      • 1970-01-01
      相关资源
      最近更新 更多