-2

I am trying to display row by row, but it shows this error:

Undefined offset: 0

Here is my code:

<?php
    $host = "localhost";
    $user = "postgres";
    $password = "20152016";
    $db = "Projet";

    $con = pg_connect("host=$host dbname=$db user=$user password=$password")
        or die ("Could not connect to server\n");
?>

<?php
    $query = "SELECT ST_ASGeoJSON(geometry) FROM poi where type='batiment'";
    $result = pg_query($con, $query);
    while ($row = pg_fetch_assoc($result))
    {
        $data = array();
        echo $data[0];
    }
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sara
  • 41
  • 7
  • possible duplicate of [Reference - What does this error mean in PHP?](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Damien Overeem Sep 13 '15 at 10:55
  • The whole top of your code is irrelevant to your question. It boils down to the last 2 lines You create an empty array (`$data = array()`) and then echo the first item in that array (`echo $data[0];`). Since it is empty, $data[0] does not exist. That is why you get the undifined offset error. – Damien Overeem Sep 13 '15 at 10:57

2 Answers2

1

Your $data array is empty and its unnecessary so it cause undefined offset.

Change this

 while ($row = pg_fetch_assoc($result))  
{  
$data = array( );
echo $data[0];
}  

to this

while ($row = pg_fetch_assoc($result))  
{  
   foreach($row as $rc) { 
          echo $rc[0];
    }
}  
Noman
  • 4,088
  • 1
  • 21
  • 36
1

Change this piece of code:

while ($row = pg_fetch_assoc($result))  
{  
$data = array( );
echo $data[0];
}  

To this:

while ($row = pg_fetch_assoc($result))  
{  
    foreach($row as $rslt)
        echo $rslt;
}  
halfer
  • 19,824
  • 17
  • 99
  • 186
  • i will define this variable in javascript code but i can't @pakistanimoon can you help me please – sara Sep 13 '15 at 11:04
  • @HawasKaPujaari: please do not use the quote device for decorative effect. The purpose of quote blocks is to hold quotes, and it is not to be used for ordinary paragraph text. Thanks. – halfer Sep 13 '15 at 11:05
  • 1
    @halfer aye aye captain! X) – DirtyBit Sep 13 '15 at 11:49
  • @sara there are many ways to access php code's output in javascript, easiest one is use ajax, hopefully u already know that. secondly u can creat a variable containing all the output and use that variable in javascript as var jsvariablename = '' –  Sep 14 '15 at 01:15