[GIS] Loading raster in postgis via raster2pgsql

pgadmin-3PHPpostgispostgresqlsql

I need to import data file to my database.
I created a web interface in order to upload file
but I have already an error

Warning: pg_query(): Query failed: ERROR: rt_raster_from_wkb: wkb size
(0) < min size (61) LINE 1: INSERT INTO
eau_param_hydro(rast,filename) VALUES('','testte… ^ in
C:\wamp\www\test\test.php on line 32

My code is :

<form method="post" action="" enctype="multipart/form-data">
     <label for="fichier">Ajouter raster :</label><br />
     <input type="file" name="fichier"  />
     <input type="submit" name="submit" value="Envoyer" /> </form> 
       <?php $name = $_FILES['fichier']['name']; $db = pg_connect('host=localhost port=5432 dbname=gisdb user=postgres >password=******');           $output =shell_exec("raster2pgsql -a -s 32629 -I -C -F -M '".$_FILES["fichier"]["tmp_name"]."' eau_param_hydro | psql -U postgres -d gisdb -h localhost -p 5432 ");         $req = exec(" SELECT * FROM '".$output."' ");
    $result = pg_query($db,"INSERT INTO eau_param_hydro(rast,filename)  >VALUES('".$req."','".$name."');");
         if (!$result) { 
         $errormessage = pg_last_error(); 
         echo "Error with query: " . $errormessage; 
         exit(); 
        }  pg_close();  ?>

in PostGIS I have a table :

CREATE TABLE eau_param_hydro ( rid serial NOT NULL, rast raster,
filename text, CONSTRAINT eau_param_hydro_pkey PRIMARY KEY (rid ),
CONSTRAINT enforce_num_bands_rast CHECK (st_numbands(rast) = 1),
CONSTRAINT enforce_srid_rast CHECK (st_srid(rast) = 4326) ) WITH (
OIDS=FALSE ); ALTER TABLE eau_param_hydro OWNER TO postgres;

— Index: eau_param_hydro_st_convexhull_idx

— DROP INDEX eau_param_hydro_st_convexhull_idx;

CREATE INDEX eau_param_hydro_st_convexhull_idx ON eau_param_hydro
USING gist (st_convexhull(rast) );

Best Answer

Here is a way to do it with just PHP, not tested. Two useful links: Writing binary files to postgres - https://stackoverflow.com/questions/11162695/store-blob-like-data-in-postgresql

-- this is a postgis function that converts a regular raster into a postgis raster http://postgis.net/docs/manual-dev/RT_ST_FromGDALRaster.html

You first of all need to do this with a parameterized query. What you are doing will not work:

 <?php $fcontents = file_get_contents($_FILES["fichier"]["tmp_name"]);
   $db = pg_connect('host=localhost port=5432 dbname=gisdb user=postgres password=******');         
   $sql = 'INSERT INTO eau_param_hydro(filename,rast)
        VALUES($1, ST_FromGDALRaster( ($2)::bytea ) );';
   $params = array($_FILES["fichier"]["name"], pg_escape_bytea($fcontents) );

  $result = pg_query_params($db, $sql, $params);
  pg_close();  ?>