How can i create a LineString geoJson with data from data base? - php

ok, so I know how to convert data from php to geojson format into point types but i dont understand how can I make this into a lineString type here is the code, so the question is how can i get the coordinates data into one array :
include('testcon.php');
$query=pg_query($connect,"SELECT number, state, data, latitude,
long "
. "FROM schema.table "
. "WHERE number = '63' AND "
. "data BETWEEN '2018-12-01 00:00:00' and '2018-12-01 23:59:59'
limit 200 ");
# Try query or error
# Build GeoJSON feature collection array
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
# Loop through rows to build feature arrays
while($row = pg_fetch_array($query)) {
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
# Pass Longitude and Latitude Columns here
'coordinates' => array($row['long'], $row['lat'])
),
# Pass other attribute columns here
'properties' => array(
'indicativ' => $row['number'],
'stare' => $row['state'],
)
);
# Add feature arrays to feature collection array
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$conn = NULL;
?>

Solved it
$pointlist=array();
while($row = pg_fetch_assoc($query)) {
$pointlist[]=array($row['long'], $row['lat']);
};
# Build GeoJSON feature collection array
$geojson = array(
'type' => 'FeatureCollection',
'features' => array(
#);
#$feature = array(
'type' => 'Feature',
'geometry' => array(
'type'=> 'LineString',
'coordinates'=> $pointlist
)));
i create an empty array and then looped through all the data from lat and long columns and than in coordinates i got the variabel

Related

Merge multidimensional array in PHP

I have a multi array and I need to combine it with other. This array is made for send in XML format to SOAP, so it need to have the correct structure.
This array is like an invoice, it have "items" which i have to repeat. So, i think in make two arrays (one have always the same structure) and add the items array.
The problem is that if I use merge, I could not put the second array in the correct key. Here an example.
This is the correct array structure:
$params = array(
'authRequest' =>
array( 'token' => 'token',
'sign' => 'sign',
'cuitRepresentada' => 'CUIT' ),
'comprobanteRequest' =>
array( 'codigoTipoComprobante' => $codtipcbte,
'numeroPuntoVenta' => $ptovta,
'numeroComprobante' => $cbte,
**'arrayItems' =>
array( 'item' =>
array(
array(
'tipo'=> $compreqitem['tipo'],
'codigoTurismo'=> $compreqitem['codTur'],
'descripcion'=> $compreqitem['descrip'],
'codigoAlicuotaIVA'=> $compreqitem['codAlic'],
'importeIVA'=> $compreqitem['impIva'],
'importeItem'=> $compreqitem['impItem'],
),
array(
'tipo'=> $compreqitem['tipo'],
'codigoTurismo'=> $compreqitem['codTur'],
'descripcion'=> $compreqitem['descrip'],
'codigoAlicuotaIVA'=> $compreqitem['codAlic'],
'importeIVA'=> $compreqitem['impIva'],
'importeItem'=> $compreqitem['impItem'],
),
),
),**
'arraySubtotalesIVA' =>
array( 'subtotalIVA' =>
array(
'codigo'=> $compreqiva['codIva'],
'importe'=> $compreqiva['importe'],
),
),
),
);
So, i build the array with "arrayItems" empty
'arrayItems' => array(),
Then i build the arrayItem array:
$arrayitems =
array('arrayItems' =>
array( 'item' =>
array(
array(
'tipo'=> $compreqitem['tipo'],
'codigoTurismo'=> $compreqitem['codTur'],
'descripcion'=> $compreqitem['descrip'],
'codigoAlicuotaIVA'=> $compreqitem['codAlic'],
'importeIVA'=> $compreqitem['impIva'],
'importeItem'=> $compreqitem['impItem'],
),
array(
'tipo'=> $compreqitem['tipo'],
'codigoTurismo'=> $compreqitem['codTur'],
'descripcion'=> $compreqitem['descrip'],
'codigoAlicuotaIVA'=> $compreqitem['codAlic'],
'importeIVA'=> $compreqitem['impIva'],
'importeItem'=> $compreqitem['impItem'],
),
),
),
);
Then i use merge to join both array:
$resultado = array_merge($params['comprobanteRequest'], $arrayitems);
Works, but the first key is deleted...
'authRequest' =>
array( 'token' => 'token',
'sign' => 'sign',
'cuitRepresentada' => 'CUIT' ),
I dont know why is deleted, maybe the merge function is not the corect way...
Thanks in advance!
If in your first array, arrayItems is always empty, then you don't need a merge, just set the value :
$params['comprobanteRequest']['arrayItems'] = $arrayItems['arrayItems'];
Of course this can be simplified, since $arrayItems contains only one key, but you get the spirit.

PHP MySQL: decrypt a column value from a MySQL row that was encrypted upon insertion and parse to JSON

Everything is working, all I want is to decrypt the db column containing the credit card number from the database with the following example:
$decp = $crypt->decrypt($encp);
the row in question is:
'Number' => $row['cardNumber'],
the entire code is:
// get the cards
$jsonresult = $conn->query("SELECT nameOnCard, cardNumber, cardType, cardDate, ccvCode
FROM cy_user_credit_cards
WHERE accountNumber='$accountNumber'");
$creditCard = [];
while ($row = mysqli_fetch_assoc($jsonresult)) {
array_push($creditCard, [
'Name' => $row['nameOnCard'],
'Number' => $row['cardNumber'],
'Type' => $row['cardType'],
'Date' => $row['cardDate'],
'ccv' => $row['ccvCode']
]);
}
// Convert the Array to a JSON String and echo it
$ccJSON = json_encode($creditCard);
echo $ccJSON;
$conn->close();
I think you would want to do something like this:
// get the cards
$jsonresult = $conn->query("SELECT nameOnCard, cardNumber, cardType, cardDate, ccvCode
FROM cy_user_credit_cards
WHERE accountNumber='$accountNumber'");
$creditCard = [];
while ($row = mysqli_fetch_assoc($jsonresult)) {
array_push($creditCard, [
'Name' => $row['nameOnCard'],
'Number' => $crypt->decrypt($row['cardNumber']),
'Type' => $row['cardType'],
'Date' => $row['cardDate'],
'ccv' => $row['ccvCode']
]);
}
// Convert the Array to a JSON String and echo it
$ccJSON = json_encode($creditCard);
echo $ccJSON;
$conn->close();
Keep in mind, You really do not want to store all of these credit card details in your database if it is not absolutely necessary. I would urge you to look elsewhere to handle credit card payments.
You can decrypt the string upon pushing your data into the array like so:
array_push($creditCard, [
'Name' => $row['nameOnCard'],
'Number' => $crypt->decrypt($row['cardNumber']),
'Type' => $row['cardType'],
'Date' => $row['cardDate'],
'ccv' => $row['ccvCode']
]);

Create PieChart with google chart api and php

I'm kinda new to google chart api, and still wiping the dust out my php knowledge, so maybe someone can help with this (IMO) basic question...
So I have this php class wich queries data from server and should post it back to my page. There is a working Line Chart in it, as you can see at the snippet below:
$rowdata = array();
$i=0;
$_POST['from'] = str_replace("/","-",$_POST['from']);
$_POST['to'] = str_replace("/","-",$_POST['to']);
$cur_date = $_POST['from'];
$sql = "SELECT DATE(entered),
COUNT(*) AS totalaccounts,
SUM(CASE WHEN facebook_username != '' THEN 1 ELSE 0 END) AS facebook,
SUM(CASE WHEN facebook_username = '' THEN 1 ELSE 0 END) AS standard
FROM Account
WHERE entered BETWEEN '". $_POST['from'] ."' AND '". $_POST['to'] ."'
GROUP BY DATE(entered)";
$result = $dbMain->query($sql);
$rows = tratarDadosParaGrafico($result);
$return = json_encode(array('cols' => $cols, 'rows' => $rows));
$data = array(
'cols' => array(
array('id' => '', 'label' => 'Date', 'type' => 'string'),
array('id' => '', 'label' => 'Total Accounts', 'type' => 'number'),
array('id' => '', 'label' => 'Total Accounts (Facebook)', 'type' => 'number'),
array('id' => '', 'label' => 'Total Accounts (Non Facebook)', 'type' => 'number')
),
'rows' => $rows
);
$chart = new Chart('LineChart');
$options = array('title' => 'Accounts');
$chart->load(json_encode($data));
echo $chart->draw('rchart', $options);
What I was trying to do was use the same query result ($data) to populate another chart, this one a pie chart... So I simply pasted the last 4 lines of code, changing the parameter when creating a new instance of Chart:
$chart = new Chart('PieChart');
$options = array('title' => 'Accounts');
$chart->load(json_encode($data));
echo $chart->draw('pchart', $options);
After this, I close the php tag and use 2 divs to show my charts...
<div id="rchart"></div>
<div id="pchart"></div>
Everything here comes from this index.php class, I haven't seen html files at all... What happens is I can see the pie chart right below the line chart, but it comes with no data within, i.e., the whole chart is grey and labeled as "Other"
What may I've done wrong? Thanks in advance!
[EDIT]
Let's say I want a Pie Chart with only 2 slices, why the code below doesn't works? (I get "Cannot read property '1' of undefined" error)
$data = array(
'cols' => array(
array('label' => 'Pie slice labels', 'type' => 'string'),
array('label' => 'Pie slice values', 'type' => 'number')
),
'rows' => array(
array('v' => intval($facebook_accounts[0]), 'type' => 'int'),
array('v' => intval($default_accounts[0]), 'type' => 'int')
)
);
$chart = new Chart('PieChart');
$options = array('title' => 'Accounts');
$chart->load(json_encode($data));
echo $chart->draw('piechart', $options);
[EDIT] Maybe this can help you helping me :)
https://groups.google.com/forum/#!topic/google-visualization-api/Wi_WOVOgzG8
Creating Pie char from mysql database using php and google charts
PieCharts don't use the same data structure as the LineCharts. PieCharts expect two columns of data: the first is the pie slice labels, and the second is the pie slice values. You will have to reconfigure your data pull to put the data in the correct format.
Edit:
Here's some sample PHP pseudo-code for building a DataTable for a PieChart:
$data = array(
'cols' => array(
array('label': 'Pie slice labels', type: 'string'),
array('label': 'Pie slice values', type: 'number')
),
'rows' => array()
);
while (/* loop over SQL results */) {
$data['rows'][] = array('c' => array(
array('v' => /* pie slice label */),
array('v' => /* pie slice value */) // use (int) or (float) to parse appropriately, as many databases output numbers as strings
));
}

Creating a GeoJson in php from MySql to use with MapBox javascript API

What I'm trying to do is very simple; get marker's data from a Mysql table with my PHP code, convert that that to a geoJson ( used by MapBox ), send that geoJson to javascript and then populate those marker into my map.
I've been reading very carefully the following two links, that apparently contains all the info I need to resolve this, but I'm not sure what I'm missing.
Here you can see an example on how to populate markers from a geoJson in MapBox;
Here you can see how to create a geoJson from a MySql table;
My sql table look like this, here is the creation code plus some dummy data;
-- phpMyAdmin SQL Dump
-- version 4.0.4.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jul 21, 2013 at 03:26 PM
-- Server version: 5.5.32-cll-lve
-- PHP Version: 5.5.0
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
--
-- Database: `pgmq`
--
-- --------------------------------------------------------
--
-- Table structure for table `mapa`
--
CREATE TABLE IF NOT EXISTS `mapa` (
`contrato` int(11) NOT NULL,
`name` varchar(60) NOT NULL,
`address` varchar(80) NOT NULL,
`lat` float(10,6) NOT NULL,
`lng` float(10,6) NOT NULL,
`type` varchar(30) NOT NULL,
PRIMARY KEY (`contrato`),
UNIQUE KEY `contrato` (`contrato`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `mapa`
--
INSERT INTO `mapa` (`contrato`, `name`, `address`, `lat`, `lng`, `type`) VALUES
(217, 'DIVANIR BRASIL DA SILVA', '47 joao carolino da silva, guaruja - sao paulo, brazil', -23.950968, -46.289585, '11'),
(233, 'ADEMIR VIEIRA', '180 dois j, guaruja - sao paulo, brazil', -23.932041, -46.206879, '11'),
(241, 'MARIA CECILIA DOS SANTOS', '81 professor carvalho pinto, guaruja - sao paulo, brazil', -23.946516, -46.290428, '11'),
(252, 'ELIETE COSTA SANTOS', '387 maria de melo rodrigues, guaruja - sao paulo, brazil', -23.667521, -46.747810, '11'),
(271, 'ROBERTO SANTOS COUTO', '62 tapajos, guaruja - sao paulo, brazil', -23.949146, -46.284588, '11'),
(275, 'UMBERTO FERREIRA SOUZA NETO', '88 tapajos, guaruja - sao paulo, brazil', -23.949162, -46.284821, '11'),
(276, 'SERGIO RICARDO DOS SANTOS', '418 joana menezes de mello faro, guaruja - sao paulo, brazil', -23.994600, -46.256866, '11'),
(278, 'MARIA APARECIDA NUNES', '80 andre reboucas, guaruja - sao paulo, brazil', -23.945040, -46.297462, '11'),
(285, 'WALTECES SOUZA DA CONCEICAO', '298 maranhao, guaruja - sao paulo, brazil', -23.942638, -46.304131, '11'),
(286, 'ROBERTO AUGUSTO DE JESUS SOUZA', '38 dois c caic cinquenta e cinco , guaruja - sao paulo, brazil', -23.994600, -46.256866, '11');
So here is my php code, where I get the data from the DB and create a GeoJson.
<?php
$connect = mysql_connect("localhost","user","password");
$mapa = "SELECT * FROM pgmq.mapa ";
$dbquery = mysql_query($mapa,$connect);
$geojson = array( 'type' => 'FeatureCollection', 'features' => array());
while($row = mysql_fetch_assoc($dbquery)){
$marker = array(
'type' => 'Feature',
'features' => array(
'type' => 'Feature',
'properties' => array(
'title' => "".$row[name]."",
'marker-color' => '#f00',
'marker-size' => 'small'
//'url' =>
),
"geometry" => array(
'type' => 'Point',
'coordinates' => array(
$row[lat],
$row[lng]
)
)
)
);
array_push($geojson['features'], $marker['features']);
}
?>
Just to test this, if a "echo json_encode($marker)" here is a sample output;
{"type":"Feature","features":{"type":"Feature","properties":{"title":"DIVANIR BRASIL DA SILVA","marker-color":"#f00","marker-size":"small"},"geometry":{"type":"Point","coordinates":"[-23.950968, -46.289585]"}}};
Now on this is what the javascript code looks like;
<script>
var map = L.mapbox.map('map', 'examples.map-20v6611k').setView([-23.948714, -46.295508], 1);
// The GeoJSON representing the two point features
var geoJson = <?php echo json_encode($marker,JSON_NUMERIC_CHECK); ?>;
// Pass features and a custom factory function to the map
map.markerLayer.setGeoJSON(geoJson);
map.markerLayer.on('click', function(e) {
e.layer.unbindPopup();
window.open(e.layer.feature.properties.url);
});
</script>
And finally the complete HTML that actually shows the map, but not the markers;
<?php
$connect = mysql_connect("localhost","user","pass");
$mapa = "SELECT * FROM pgmq.mapa ";
$dbquery = mysql_query($mapa,$connect);
$geojson = array( 'type' => 'FeatureCollection', 'features' => array());
while($row = mysql_fetch_assoc($dbquery)){
$marker = array(
'type' => 'Feature',
'features' => array(
'type' => 'Feature',
'properties' => array(
'title' => "".$row[name]."",
'marker-color' => '#f00',
'marker-size' => 'small'
//'url' =>
),
"geometry" => array(
'type' => 'Point',
'coordinates' => array(
$row[lat],
$row[lng]
)
)
)
);
array_push($geojson['features'], $marker['features']);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' />
<script src='//api.tiles.mapbox.com/mapbox.js/v1.3.1/mapbox.js'></script>
<link href='//api.tiles.mapbox.com/mapbox.js/v1.3.1/mapbox.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
var map = L.mapbox.map('map', 'examples.map-20v6611k').setView([-23.948714, -46.295508], 1);
// The GeoJSON representing the two point features
var geoJson = <?php echo json_encode($marker,JSON_NUMERIC_CHECK); ?>;
// Pass features and a custom factory function to the map
map.markerLayer.setGeoJSON(geoJson);
map.markerLayer.on('click', function(e) {
e.layer.unbindPopup();
window.open(e.layer.feature.properties.url);
});
</script>
</body>
</html>
So, what am I missing? one thing I notice is that the output of my geoJson has " in the geometry array, while the one used in the MapBox example don't;
var geoJson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {
title: 'Washington, D.C.',
'marker-color': '#f00',
'marker-size': 'large',
url: 'http://en.wikipedia.org/wiki/Washington,_D.C.'
},
geometry: {
type: 'Point',
coordinates: [-77.03201, 38.90065]
}
},
{
type: 'Feature',
properties: {
title: 'Baltimore, MD',
'marker-color': '#f00',
'marker-size': 'large',
url: 'http://en.wikipedia.org/wiki/Baltimore'
},
geometry: {
type: 'Point',
coordinates: [-76.60767, 39.28755]
}
}]
};
Can anyone help me? there hasn't any real complication, i think it's just a data formatting problem or the way that I'm sending the GeoJson to the JS.
Thanks in advance!
I've just notice that this line;
var geoJson = <?php echo json_encode($marker,JSON_NUMERIC_CHECK); ?>;
should be;
var geoJson = <?php echo json_encode($geojson,JSON_NUMERIC_CHECK); ?>;
and in that case the result is;
var map = L.mapbox.map('map', 'examples.map-20v6611k').setView([-23.948714, -46.295508], 1);
// The GeoJSON representing the two point features
var geoJson = ;
// Pass features and a custom factory function to the map
map.markerLayer.setGeoJSON(geoJson);
map.markerLayer.on('click', function(e) {
e.layer.unbindPopup();
window.open(e.layer.feature.properties.url);
});
Have a look at this: https://github.com/bmcbride/PHP-Database-GeoJSON
You are returning array instead of Json data. This is what it should look like
<?php
/*
* Title: MySQL Points to GeoJSON
* Notes: Query a MySQL table or view of points with x and y columns and return the results in GeoJSON format, suitable for use in OpenLayers, Leaflet, etc.
* Author: Bryan R. McBride, GISP
* Contact: bryanmcbride.com
* GitHub: https://github.com/bmcbride/PHP-Database-GeoJSON
*/
# Connect to MySQL database
$conn = new PDO('pgsql:host=localhost;dbname=mypostgisdb','myusername','mypassword');
# Build SQL SELECT statement including x and y columns
$sql = 'SELECT *, x AS x, y AS y FROM mytable';
/*
* If bbox variable is set, only return records that are within the bounding box
* bbox should be a string in the form of 'southwest_lng,southwest_lat,northeast_lng,northeast_lat'
* Leaflet: map.getBounds().pad(0.05).toBBoxString()
*/
if (isset($_GET['bbox']) || isset($_POST['bbox'])) {
$bbox = explode(',', $_GET['bbox']);
$sql = $sql . ' WHERE x <= ' . $bbox[2] . ' AND x >= ' . $bbox[0] . ' AND y <= ' . $bbox[3] . ' AND y >= ' . $bbox[1];
}
# Try query or error
$rs = $conn->query($sql);
if (!$rs) {
echo 'An SQL error occured.\n';
exit;
}
# Build GeoJSON feature collection array
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
# Loop through rows to build feature arrays
while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
$properties = $row;
# Remove x and y fields from properties (optional)
unset($properties['x']);
unset($properties['y']);
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array(
$row['x'],
$row['y']
)
),
'properties' => $properties
);
# Add feature arrays to feature collection array
array_push($geojson['features'], $feature);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$conn = NULL;
?>
You're close, and are on the right track here:
one thing I notice is that the output of my geoJson has " in the geometry array, while the one used in the MapBox example don't;
Yes, you need to make those quotes go away! Looking at your sample output you're getting a string rather than an array for the value of the 'coordinates' key in your array.
I'm not sure why this is the case based on your sample code, but something like this should work:
$geojson = array( 'type' => 'FeatureCollection', 'features' => array());
while($row = mysql_fetch_assoc($dbquery)){
$marker = array(
'type' => 'Feature',
'properties' => array(
'title' => $row['name'],
'marker-color' => '#f00',
'marker-size' => 'small'
),
'geometry' => array(
'type' => 'Point',
'coordinates' => array(
$row['lat'],
$row['lng']
)
)
);
array_push($geojson['features'], $marker);
}
Check this line
// The GeoJSON representing the two point features
var geoJson = ;
// Pass features and a custom factory function to the map
Try to add quotes around the php output
var geoJson = '';
$marker = array(
'type' => 'Feature',
//'features' => array(
//'type' => 'Feature',
'properties' => array(
'title' => $row->name,
'marker-color' =>'#0F8C29',
'marker-size' => 'small'
//'url' =>
),
"geometry" => array(
'type' => 'Point',
'coordinates' => array(
$row->lng,
$row->lat
)
)
//)
);
array_push($geojson['features'], $marker);
Final answer:
<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'pgmq');
$connect = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
$mapa = "SELECT * FROM mapa ";
$dbquery = mysqli_query($connect,$mapa);
$geojson = array( 'type' => 'FeatureCollection', 'features' => array());
while($row = mysqli_fetch_assoc($dbquery)){
$marker = array(
'type' => 'Feature',
'properties' => array(
'title' => $row['name'],
'marker-color' => '#f00',
'marker-size' => 'small'
),
'geometry' => array(
'type' => 'Point',
'coordinates' => array(
$row['lng'],
$row['lat']
)
)
);
array_push($geojson['features'], $marker);
}
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
?>
I believe, it will help others.
You can verify the response at: https://geojsonlint.com/

How to search in fulltext index using php in mongodb

I'm using mongodb 2.4 and added fulltext index to the "title" field in one the collection. How should I search something in that field using php?
This is the code I use right now:
$params = array(
'_id' => array(
'$gt' => (int)$gt
)
);
$r = $this->collection->find( $params )->limit($limit);
This seem to be the answer to my question:
<?php
$result = $db->command(
array(
'text' => 'bar', //this is the name of the collection where we are searching
'search' => 'hotel', //the string to search
'limit' => 5, //the number of results, by default is 1000
'project' => Array( //the fields to retrieve from db
'title' => 1
)
)
);
http://www.php.net/manual/en/mongodb.command.php#111891

Categories