How to access array element

I’m trying to generate pdf using FPDF and naming filename based on username…It is accessing the first array position perfectly but from second index it is displaying as null. What can be the mistake…??

Below is my code

       require '../fpdf/fpdf.php';
       require 'start.php';

      use Aws\Exception\AwsException;

      $location = "mangalore";

      $db     =   getConnection();
     $query   = "SELECT first_name FROM customer_info where location = '$location'";
     $execute = $db->query($query);
     $result  = $execute->fetchAll(PDO::FETCH_ASSOC);

      print_r($result);
     
      for($i = 0; $i < $len; $i++)
     {
      var_dump($i);
      echo "<br>";

      var_dump($result[$i]['first_name']);
      echo "<br>";


      $pdf = new FPDF();
      $pdf->AddPage();

      $pdf->SetFont('Arial', 'B', 14);
      $txt = "Legal Document of ".$result[$i]['first_name'];
      $pdf->Cell(180, 0, $txt, 0, 1, 'C');
      $pdf->Line(5, 20, 200, 20);

      $docname = $result[$i]['first_name'] . ".pdf";
      var_dump($docname);
      echo "<br>";
      $filepath = "../file/{$docname}";
      $pdf->Output($filepath, 'F');

    //s3 client
    try {
           $result = $S3->putObject([
            'Bucket' => $config['S3']['bucket'],
            'Key' => "AWS_PATH",
            'Body' => fopen($filepath, 'rb'),
            'ACL' => 'public-read'
        ]);


        var_dump($result["ObjectURL"]);
        echo "<br>";
        } catch (S3Exception $e) {
        echo $e->getMessage() . "\n";
       }
   }

    function getConnection() {
    $dbhost="localhost";
    $dbuser="root";
    $dbpass="";
    $dbname="dbname";
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
    }

Below is my output

    Array ( [0] => Array ( [first_name] => XYZ) [1] => Array ( [first_name] =>ABC ) [2] => Array ( [first_name] => PQR ) ) 
 
    int(0) 
    string(6) "XYZ" 
    string(10) "XYZ.pdf" 

    int(1) 
    NULL 
    string(4) ".pdf" 
   
    int(2) 
    NULL 
    string(4) ".pdf"

Spot the mistake:

$result  = $execute->fetchAll(PDO::FETCH_ASSOC);

and then, inside the loop:

  $result = $S3->putObject([

By the time you get to the second iteration, your results array has gone.

1 Like

Thank You @droopsnoot…Spotted it immediately when i started tracing it…

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.