i'm using this code for nearby search,i have problem,how get results?
results = 0 then ,i want to check radius=1 to 1000 ,results = 1 then i want to getAddress how i do that?
function getAddress($la, $lo){
$ur= "http://maps.googleapis.com/maps/api/place/nearbysearch/json?location=".$la.",".$lo."&radius=10&sensor=true&key=AIzaSyA0JD_Z2Uo2AfnDTejQFWHAXOIaRRpjF8c";
$json = file_get_contents($ur);
$data = json_decode($json);
$status = $data->status;
$name= '';
if($status == "OK"){
$addr = $data->results[0]->formatted_address;
}
return $addr;
}
echo getAddress("6.154841","80.700845");
Related
I'm fairly new to WordPress and SQL. I have a contact form that I want to have the data be submitted to my WordPress database but only if the data that has been entered has not been entered before.
This is what i have so far, which sends data to my database when form is submitted.
if(isset($_POST['contact_us'])) {
$invalidContact = "<h5 class='invalidBooking'> Nope try again</h5>";
$successContact = "<h5 class='invalidBooking'> Message Sent!</h5>";
$table_name='contact_table';
global $wpdb;
$contact_name = esc_attr($_POST['contact_name']);
$contact_email = sanitize_email($_POST['contact_email']);
$subject = esc_attr($_POST['subject']);
$message = esc_attr($_POST['message']);
$error= array();
if (empty($contact_name)) {
$error['name_invalid']= "Name required";
}
if (empty($contact_email)){
$error['email_invaild']= "Email required";
}
// Im guessing some code here to check if row exists in database
if (count($error) >= 1) {
echo $invalid;
}
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
echo $successContact;
}
}
You may try this code
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$query = "SELECT * FROM $table_name WHERE 'Contact_Name'= '$contact_name' AND 'Contact_Email' = '$contact_email' AND 'Contact_Subject' = '$subject' AND 'Contact_Message' = '$message'";
$query_results = $wpdb->get_results($query);
if(count($query_results) == 0) {
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
}
}
Hope this works for you.
fetch data using this code
$query = "SELECT * FROM {$wpdb->prefix}table WHERE column = 1";
echo $query;
$results = $wpdb->get_results($query);
and then you know what to do...
i can't get more than one return in this json. when the original query returns 90k results.
i can't figure out what's hapening.
also the return i get isn't organized as it should. it return the following
{"material":["R8190300000","0"],"grid":["R8190300000","0"]}
sorry to ask this i have been looking for an answer but couln't get it in the internet.
<?php
$link = mysqli_connect("localhost","blablabla","blablabla","blablabla");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query =" SELECT material,grid FROM ZATPN";
if( $result = mysqli_query( $link, $query)){
while ($row = mysqli_fetch_row($result)) {
$resultado['material']=$row;
$resultado['grid']=$row;
}
} else {
echo"doesnt work";
}
file_put_contents("data.json", json_encode($resultado));
?>
The problem is that you are overriding the value for the array keys:
$resultado['material']=$row;
$resultado['grid']=$row;
At the end you will have only the last 2 rows; I suggest you to use something like:
$resultado['material'][] = $row;
$resultado['grid'][] = $row;
This will save you pair rows in $resultado['grid'] and unpaired rows in $resultado['material'];
After the information in comments you can use this code:
$allResults = array();
while ($object = mysqli_fetch_object($result)) {
$resultado['id'] = $object->id;
$resultado['name'] = $object->name;
$resultado['item'] = $object->item;
$resultado['price'] = $object->price;
$allResults[] = $resultado;
}
file_put_contents("data.json", json_encode($allResults));
I make service from json but i have problem to show url in json, this url http://git.drieanto.net/LagiDimanaAPI/index.php/user/get_following/1 i try to show url from database but in json show "avatar":"http:\/\/git.drieanto.net\/LagiDimanaAPI\/assets\/image\/avatar\/edwin.png".
how to make to show normal url like this http://git.drieanto.net/LagiDimanaAPI/assets/image/avatar/edwin.png
i used codeigniter this the code
function get_following($id_follower) {
if ($this->muser->cek_following($id_follower) == TRUE) {
$query = $this->muser->get_list_id($id_follower);
$feedback["following"] = array();
foreach ($query->result() as $row) {
$query_list_user = $this->muser->get_all_name_user_from_id($row->id_user);
if ($query_list_user->num_rows() > 0) {
$row_ = $query_list_user->row();
$query_status = $this->muser->get_status($row_->id_user);
$query_status->num_rows();
$row2 = $query_status->row();
$response['status'] = $row2->status;
$response['regid'] = $row_->regid;
$response['id_user'] = $row_->id_user;
$response['email'] = $row_->email;
$response['nama'] = $row_->nama;
$response['jenis_kelamin'] = $row_->jenis_kelamin;
$response['tanggal_lahir'] = $row_->tanggal_lahir;
$response['instansi'] = $row_->instansi;
$response['jabatan'] = $row_->jabatan;
$response['avatar'] = $row_->avatar;
$feedback['success'] = 1;
} else {
$feedback['success'] = 0;
}
array_push($feedback["following"], $response);
}
$feedback['success'] = 1;
echo json_encode($feedback);
} else {
$feedback['success'] = 0;
echo json_encode($feedback);
}
}
thanks
It's just escaping the forwardslashes. You can use str_replace($search_char, $replace_char, $string_to_search), to remove them.
$stuff = json_decode($response);
$url = str_replace("\\", "", $stuff['url']);
It does sound like you're not decoding the JSON because I do believe PHP will unescape all of that stuff for you automatically.
I've been using Google geocoding v3 for about 6 months but all of a sudden it's stopped working (I get a 610 error). It's only stopped in the last week or so.
Then I came across this (see the pink box at the top of the page!): https://developers.google.com/maps/documentation/geocoding/v2/
I've read through all the documentation and not sure where to start!
I'm hoping it's a small change as it's taken a long time to get this far, can anyone help?
[See the full site here][1]
UPDATE:
require("database.php");
// Opens a connection to a MySQL server
$con = mysql_connect("localhost", $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("teamwork_poh", $con);
$company = get_the_title();
$address = get_field('address_line_1');
$city = get_field('town_/_city');
$post_code = get_field('post_code');
$link = get_permalink();
$type = get_field('kind_of_organisation');
$sql = sprintf("select count('x') as cnt from markers where `name` = '%s'", mysql_real_escape_string($company));
$row_dup = mysql_fetch_assoc(mysql_query($sql,$con));
if ($row_dup['cnt'] == 0) {
mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`, `link`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '".$type."', '".$link."')");
}
wp_reset_query();
require("database.php");
define("MAPS_HOST", "maps.googleapis.com");
define("KEY", "(my key)");
// Opens a connection to a MySQL server
$connection = mysql_connect("localhost", $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die("Can\'t use db : " . mysql_error());
}
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
//Initialize delay in geocode speed
$delay=0;
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/json?address=";
while ($row = #mysql_fetch_assoc($result)) {
if (!($row['lat'] * 1)) {
$geocode_pending = true;
while ($geocode_pending){
$address = $row["address"];
$id = $row["id"];
$request_url = $base_url . "" . urlencode($address) ."&sensor=false";
sleep(0.1);
$json = file_get_contents($request_url);
$json_decoded = json_decode($json);
$status = $json_decoded->status;
if (strcmp($json_decoded->status, "OK") == 0) {
$geocode_pending = false;
$lat = $json_decoded->results[0]->geometry->location->lat;
$lng = $json_decoded->results[0]->geometry->location->lng;
// echo 'here';
$query = sprintf("UPDATE markers " .
" SET lat = '%s', lng = '%s' " .
" WHERE id = '%s' LIMIT 1;",
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
echo $id;
if (!$update_result) {
die("Invalid query: " . mysql_error());
}
}
else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocode. ";
echo "Received status " . $status . "\n";
}
// usleep($delay);
}
}
}
As you are storing the coordinates in database it would be best to geocode when you insert new record.
ie
require("dbinfo.php");//Your database parameters
//Connect to database
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
//Prepare query
$name = "%".$company."%";//Wildcard for PDO paramerter
$countSql = "SELECT COUNT(*) FROM markers WHERE `name` LIKE ?";
$countStmt = $dbh->prepare($countSql);
// Assign parameter
$countStmt->bindParam(1,$name);
//Execute query
$countStmt->execute();
// check the row count
if ($countStmt->fetchColumn() == 0) { #1 EDIT changed >0 to ==0
echo "No row matched the query."; //EDIT From Row
$q =$address.','.$city.','.$post_code.',UK';
echo "\n";
$base_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=";
$request_url = $base_url.urlencode($q)."&sensor=false";
$xml = simplexml_load_file($request_url) or die("url not loading");
if($xml->status=="OK"){#2
// Successful geocode
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
$insertSql ="INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`, `link`) VALUES (?,?,?,?,?,?)";
$insertStmt = $dbh->prepare($insertSql);
// Assign parameter
$insertStmt->bindParam(1,$company);
$insertStmt->bindParam(2,$address);
$insertStmt->bindParam(3,$lat);
$insertStmt->bindParam(4,$lng);
$insertStmt->bindParam(5,$type);
$insertStmt->bindParam(6,$link);
//Execute query
$insertStmt->execute();
} #2
else{
"No rows inserted.";
}#2
} #1
else {#1
echo "Rows matched the query."; //EDIT From No row
} #1
}// End try
catch(PDOException $e) {
echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", myFile.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
I have converted your code to PDO as it is advisable to stop using mysql_functions as these a deprecated.
I have left you to implement how you will deal with geocoding not returning coordinates. You can also check and deal with the following status codes
OVER_QUERY_LIMIT
ZERO_RESULTS
REQUEST_DENIED
INVALID_REQUEST
See pastebin For status code implementation
Going by our earlier comments, there are just a couple of changes required that should get you back on your feet.
These are, changing the address for v3 geocoding
define("MAPS_HOST", "maps.googleapis.com");
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/xml?";
$request_url = $base_url . "address=" . urlencode($address) . "&sensor=false";
And secondly changing the path in the returned xml file for setting lat/long
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = split(",", $coordinates);
// Format: Longitude, Latitude, Altitude
$lat = $coordinatesSplit[1];
$lng = $coordinatesSplit[0];
Can be completely replaced with
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
The next piece about stopping it from going over geocoding limits. What you need to do is set a simple check before you run through the geocoding.
while ($row = #mysql_fetch_assoc($result)) {
if (!($row['lat'] * 1)) {// add this line
$geocode_pending = true;
while ($geocode_pending){
//do geocoding stuff
}
}
}// add this close
}
We are trying to interface between a MySQL database and Google API using ajax and php (on line 3 "phpsqlajax_dbinfo.php" dedfines the database info). We want to create a marker with the lat/long from Google API, but we get the fatal error on "add(Child)"
Actual error message : "Call to a member function addChild() on a non-object"
How can we get the db to register and store the info?
<?php
require_once("phpsqlajax_dbinfo.php");
$xml = ("mapPointInfo.xml") ;
$newLatLng = $_POST['latlng']; //new markers LatLng
$newLatLng = substr($newLatLng, 1, -1); //removes first and last characters of
newLatLng which are ( and )
list($newLat, $newLng) = explode(",", $newLatLng);
//$newLng = substr($newLng, 1, 0);
$locName = $_POST['geoNameMarker']; //geocoded or simple incremented site name
$markerComment = $_POST['createMarker']; //comment entered by user
$userName = $_POST['user']; //acquire username from session
$voteValue = "likes"; //acquire vote value if any
date_default_timezone_set('America/New_York');
$timeStamp = date("m/d/Y G:i"); //get timestamp
year:month:date:hour:minutes:seconds (example: 11:6:31:14:31:42)
if($markerComment == null || $markerComment == '' || $markerComment == ' '){
$markerComment = ' ';
}
$markerComment = htmlentities($markerComment, ENT_QUOTES);
$locName = htmlentities($locName, ENT_QUOTES);
$marker = $xml->addChild('marker');
$marker->addAttribute('lat', $newLat);
$marker->addAttribute('lng', $newLng);
$marker->addAttribute('name', $locName);
$marker->addAttribute('type', 'user-sug');
$comment = $marker->addChild('comment', $markerComment); //add information to
latest/last marker
$comment->addAttribute('user', $userName);
$comment->addAttribute('vote', 'likes');
$comment->addAttribute('time', $timeStamp);
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
header ('http://www.wmuhotspotmap.org/');
exit();
?>
The fatal error? You get a fatal error. What was it? I'm guessing it has something to do with the fact that $xml is a string, but you're for some reason doing $xml->addChild() as if it were an object with functions.