MySQL Query not working in MySQLi but works in MySQL - php

I'm putting together an API for an iOS app and need to get locations nearby a geo coordinate.
I tried this query in mysqli and it returns no results. When I do it in a regular mysql_query it works perfectly. I also tested the query in phpmyadmin where it completes successfully as well.
SELECT id, name, address, city, state, longitude, latitude, ( $miles * acos( cos( radians($latitude) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( latitude ) ) ) ) AS distance
FROM locations HAVING distance < $distance ORDER BY distance LIMIT 0, 20
This is the query with the variables filled in:
SELECT id, name, address, city, state, longitude, latitude, ( 3959 * acos( cos( radians(40.735767) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-73.991806) ) + sin( radians(40.735767) ) * sin( radians( latitude ) ) ) ) AS distance
FROM locations HAVING distance < 25 ORDER BY distance LIMIT 0, 20
Is there something I'm missing why it will not work in mysqli?
This is the working mysql query code
mysql_connect('localhost', 'test', 'test') or die(mysql_error());
mysql_select_db('testdb') or die(mysql_error());
$locations = array();
$miles = 3959;
$distance = 25;
$latitude = "40.735767";
$longitude = "-73.991806";
$data = mysql_query("SELECT id, name, address, city, state, longitude, latitude, ( $miles * acos( cos( radians($latitude) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( latitude ) ) ) ) AS distance
FROM locations HAVING distance < $distance ORDER BY distance LIMIT 0, 20")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data)) {
array_push($locations, $row);
}
I'm using MysqliDb Class https://github.com/ajillion/PHP-MySQLi-Database-Class so that should work as follows
$row = $db->rawQuery("SELECT id, name, address, city, state, longitude, latitude, ( ? * acos( cos( radians(?) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( latitude ) ) ) ) AS distance
FROM locations HAVING distance < ? ORDER BY distance LIMIT 0, 20", array($miles, $latitude, $longitude, $latitude, $distance));
if (count($row) > 0){
// if found, return JSON response
echo json_encode($row[0]);
}
Even when I use the basic template I found for mysqli it fails.
$locations = array();
$miles = 3959;
$distance = 25;
$latitude = "40.735767";
$longitude = "-73.991806";
// Connect to database
$link = mysqli_connect('localhost','test','test','testdb');
// Check for Errors
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
// Prepare Query
$query = "SELECT id, name, address, city, state, longitude, latitude, ( $miles * acos( cos( radians($latitude) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin( radians( latitude ) ) ) ) AS distance
FROM locations HAVING distance < $distance ORDER BY distance LIMIT 0, 20";
// Escape Query
$query = mysqli_real_escape_string($link,$query);
// Perform Query
if($result = mysqli_query($link,$query)){
// Cycle through results
while($row = mysqli_fetch_object($result)){
array_push($locations, $row);
}
// Free Result Set
mysqli_free_result($result);
}
// Close Connection
mysqli_close($link);

Is there something I'm missing why it will not work in mysqli?
No.
Both mysql and mysqli APIs run your queries exactly the same way.
Look for the typos. And other errors of the kind.

Related

Nearest cities from latitude and longitude in Laravel

How to find nearest cities(user location[lat, long]) from latitude and longitude in PHP Laravel?
Table Structure :
locations: 'lon, lat'
user location: 'lon, lat'
$loc = explode(',', $request->get('location'));
$results = Agent::select(Agent::raw('SELECT id, ( 3959 * acos( cos( radians(' . $loc[0] . ') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(' . $loc[1] . ') ) + sin( radians(' . $loc[0] .') ) * sin( radians(lat) ) ) ) AS distance FROM articles HAVING distance < ' . 200 . ' ORDER BY distance') )->get();
$agents = \App\Agent::
where('name','like','%'.$request->get('text').'%')
->orWhere('manager','like','%'.$request->get('text').'%')
->orWhere('address','like','%'.$request->get('text').'%')
->orWhere('phone','like','%'.$request->get('text').'%')->get();
foreach ($agents as $agent) {
$agent->location = explode(',', $agent->location);
}
return $agents;

SQL query by latitude and longitude is returned 'null' using php

I'm trying to return results by latitude and longitude in me BD.
I have this script. It works fine when I do the phpmyadmin
SELECT `loc` . * , (
(
(
ACOS( SIN( ( 4.6665578 * PI( ) /180 ) ) * SIN( (
`latitude_advertiser` * PI( ) /180 ) ) + COS( ( 4.6665578 * PI( ) /180 ) ) * COS( (
`latitude_advertiser` * PI( ) /180 )
) * COS( (
(
- 74.0524521 - `longitude_advertiser`
) * PI( ) /180 )
)
)
) *180 / PI( )
) *60 * 1.1515
) AS `distance`
FROM `user_profile_` `loc`
HAVING `distance` <1
LIMIT 0 , 30
However, when I try to do the similar procedure using php my query Returns How Empty.
$connect = mysqli_connect('localhost','root','');
$db = mysqli_select_db($connect, 's2_001') or die ('Erro #1010');
$distance = 10;
$latitude = 4.6665578;
$longitude = -74.0524521;
$sql = "SELECT `loc`.*, (((acos(sin(($latitude*pi()/180)) * sin((`latitude_advertiser`*pi()/180))+cos(($latitude*pi()/180)) * cos((`latitude_advertiser`*pi()/180)) * cos((($longitude - `longitude_advertiser`)*pi()/180))))*180/pi())*60*1.1515) AS `distance` FROM `user_profile_` `loc` HAVING `distance` < 1";
$query = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($query)){
echo $row['id'] . '-' . $row['distance'] . '<br>';
}
echo mysqli_num_rows($query); // no line here
echo $sql; // test query, working in phpmyadmin

Nearby location in Yii

I want to show Merchant details approximately 60 miles distance through the User current location,
Below My coding,
$criteria = new CDbCriteria;
$criteria->select = '*, ( 3959 * acos( cos( radians(' . $currentlatval . ') ) * cos( radians( lat ) ) '
. '* cos( radians( lng ) - radians(' . $currentlngval . ') ) '
. '+ sin( radians(' . $currentlatval . ') ) * sin( radians( lat ) ) ) ) AS distance ';
$criteria->having = ("distance < 60");
$criteria->group = 'uid';
$results2 = Merchant::model()->findAll($criteria);
Its Working Properly,In the above code it check only attribute lat and lng,But I want to also check attribute city_lat and city_lng in above code How to write to check both attribute?

Store values of SQL query in variables

I have a SELECT SQL statement that returns a Latitude, Longitude and Distance as result (using the Haversine formula). Now I need to store these values as variables within the PHP script as I need to do further processing on the results. Can anyone tell me how I can do this?
Here is my SQL Statement
UPDATED
$query = $db->prepare("SELECT `Latitude`, `Longitude`, (6378160 * acos( cos( radians(:latitude) ) * cos( radians( Latitude ) ) * cos( radians( Longitude ) - radians(:longitude) ) + sin( radians(:latitude) ) * sin( radians( Latitude ) ) ) ) AS distance FROM `mytable` HAVING distance < :radius ORDER BY distance;");
// Assign parameters
$query->bindParam(':latitude',$newLatitude);
$query->bindParam(':longitude',$newLongitude);
$query->bindParam(':radius',$radius);
//Execute query
$query->execute();
$q = $db->query($query);
$q->setFetchMode(PDO::FETCH_ASSOC);
// fetch
while($r = $q->fetch()){
$eLatitude = $r->Latitude;
$eLongitude = $r>Longitude;
$distance = $r->Distance;
}
I updated my php code above. Is this code's syntax correct? Or the way I'm doing it is all wrong?
PDO::FETCH_ASSOC: returns an array indexed by column name Manual
while($r = $q->fetch()){
echo $r['Latitude']. "\n"; //Or do what ever instead of echo
echo $r['Longitude']. "\n";
echo $r['Distance']. "\n";
}
ie XML
while($r = $q->fetch()){
$node = $dom->createElement("marker");
$newnode->setAttribute("lat", $r['Latitude']);
$newnode->setAttribute("lng", $r['Longitude']);
$newnode->setAttribute("distance", $r['Distance']);
}
ie JSON
while($r = $q->fetch()){
data[] = $r;
}
you can use
$queryresult = mysql_query("SELECT `Latitude`, `Longitude`, (6378160 * acos( cos( radians(:latitude) ) * cos( radians( Latitude ) ) * cos( radians( Longitude ) - radians(:longitude) ) + sin( radians(:latitude) ) * sin( radians( Latitude ) ) ) ) AS distance FROM `mytable` HAVING distance < :radius ORDER BY distance;");
if (!$queryresult) {
echo 'Error ' . mysql_error();
exit;
}
$resultrow = mysql_fetch_row($queryresult);
echo $resultrow[0]; // this will be latitude
echo $resultrow[1]; // this will be longitude

XML data can't be displayed from mysql using php

I'm following this tutorial when I found out, I can't view the expected output because I can't view my data in xml format. I have change the configuration data a little bit, didn't know if it was the cause of malfunction?
<?php
// Get parameters from URL
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysql_connect (localhost, 'root', '12345678');
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db('demo', $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
mysql_real_escape_string($center_lat),
mysql_real_escape_string($center_lng),
mysql_real_escape_string($center_lat),
mysql_real_escape_string($radius));
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
}
echo $dom->saveXML();
?>
I am expecting to get a similar result like this http://gmaps-samples.googlecode.com/svn/trunk/articles-phpsqlsearch/phpsqlsearch_expectedoutput.xml but nothing appears. It seems like it doesn't have any data but I have already imported the data in my mysql.
First pass for issues:
<?php
// Get parameters from URL
$center_lat = ( isset( $_GET["lat"] ) ? $_GET["lat"] : 0 ); # You could replace these "0"s with the
$center_lng = ( isset( $_GET["lng"] ) ? $_GET["lng"] : 0 ); # Lat/Lng of a default location.
$radius = ( isset( $_GET["radius"] ) ? $_GET["radius"] : 10 ); # Again, default radius.
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
if( !( $connection = mysql_connect( 'localhost' , 'root' , '12345678' ) ) ) # The SQL Server address must be a string or IP address
die( "MySQL Error - Failed to connect to Server : " . mysql_error() );
// Set the active mySQL database
if( !mysql_select_db( 'demo' , $connection ) );
die( "MySQL Error - Failed to connect to Database : " . mysql_error() );
// Search the rows in the markers table
$query = sprintf( "SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
mysql_real_escape_string( $center_lat ),
mysql_real_escape_string( $center_lng ),
mysql_real_escape_string( $center_lat ),
mysql_real_escape_string( $radius ) );
$result = mysql_query( $query );
if( !$result )
die( "MySQL Error - Invalid query: " . mysql_error() . ' "'.$query.'"' ); # During debugging, echo the SQL Statement on Error
if( !headers_sent() )
header( "Content-type: text/xml" );
// Iterate through the rows, adding XML nodes for each
if( mysql_num_rows( $result ) ){
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
}
}else
die( 'MySQL Error - No Records Returned "'.$query.'"' );
echo $dom->saveXML();
?>
Give that a go, and let us know any further error messages you are seeing.
I have the same problem, there're no data, here'is the error
MySQL Error - No Records Returned "SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('37') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('-122') ) + sin( radians('37') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '25' ORDER BY distance LIMIT 0 , 20"
database is populated and I send get vars, like this:
http://localhost/superga/lib/phpsqlsearch_genxml.php?lat=37&lng=-122&radius=25
thanks
I am following the same tutorial and have hit a bend in the road at the same point.
I have followed all suggestions above and still have no resolve.
My error is;
This page contains the following errors:
error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.
Anyone get it to work?
Paula

Categories