简体   繁体   中英

Retrieve data from array

I have a minor problem where my code store the value and can run as usual, but when I want to display it again, the value won't display and the error is:

Notice: Undefined variable: result_c in C:\\xampp\\htdocs\\eAttendance\\*******.***php on line 91

Which is:

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

My question is:

  1. Why I cant call back my variable inside $result_c ?
  2. What should I do? do you have any ideas?
  3. What is the appropriate method to make this coding successful?

I made this code because I wanted to calculate all the values in array stored inside $result_c to become average percentage of attendance.

<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>

Instead of <?php echo $GLOBALS['result_c'] ?> why can't you just output <?php echo $result_c ?> ? Or am I not understanding correctly.

Also I would use prepared statements. Here is an example: http://forums.phpfreaks.com/topic/285929-pdo-in-a-php-class/#entry1467894

It seems you are injecting data straight from the client into your db call leaving you wide open to attack!

Try declaring $result_c outside the while loop, so you don't have to use $GLOBALS to cope with the variable scope issue you're having. Furthermore, the use of $GLOBALS isn't recommended.

Extra advise: I'd recommend working on your naming conventions so we can understand your code easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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