This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 5 years ago.
I want to display the nearest location around me by the following code
<?php
$lat = "27.7350758";
$long = "85.3102946";
$result = $conn->query( 'SELECT * , (3956 * 2 * ASIN(SQRT( POWER(SIN(( $lat - college_lat) * pi()/180 / 2), 2) +COS( $lat * pi()/180) * COS(college_lat * pi()/180) * POWER(SIN(( $long - college_lon) * pi()/180 / 2), 2) ))) as distance from colleges having distance <= 10 order by distance' );
if ( $result->num_rows>0 ) {
// output data of each row
while( $row = $result->fetch_assoc() ) {
echo '<div class="category"><div class="cover" style="background-image: url(img/animation.jpg);"><div>'; ?>
<td><?php echo $row[ "college_name" ]; ?></td>
<?php
echo '</div></div><span class="counter ">Courses : <span>' . $row[ "college_courses" ] . '</span></span>';
echo '<span class="counter "> Distance : <span>' . $row[ "college_address" ] . '</span></span>';
echo '<span class="near-you"> <p>'. substr( $row[ "college_desc" ], 0 , 100) . '</p> </span></div>'; ?>
Read More...
<?php
}
} else {
echo "Colleges Not Found Please add";
}
?>
When i run this code following error will display
Notice: Trying to get property of non-object in C:\xampp\htdocs\college\index.php on line 56
Colleges Not Found Please add
If I remove $lat and $long, then keep the value on query it works.
What is my mistake please suggest me. Thank you
change your query as below. change ' to " otherwise value will not interpreted:
$result = $conn->query( "SELECT * , (3956 * 2 * ASIN(SQRT( POWER(SIN(( $lat - college_lat) * pi()/180 / 2), 2) +COS( $lat * pi()/180) * COS(college_lat * pi()/180) * POWER(SIN(( $long - college_lon) * pi()/180 / 2), 2) ))) as distance from colleges having distance <= 10 order by distance" );
What is the difference between single-quoted and double-quoted strings in PHP?
I think, that is because, value $lat and $long is treated as string. You could better use prepared statement and bind these variables.
$stmt = $mysqli->prepare("SELECT * , (3956 * 2 * ASIN(SQRT(POWER(SIN((? - college_lat) * pi()/180 / 2), 2) + COS(? * pi()/180) * COS(college_lat * pi()/180) * POWER(SIN(( ? - college_lon) * pi()/180 / 2), 2) ))) as distance from colleges having distance <= 10 order by distance");
$stmt->bind_param('ddd', $lat, $lat, $long);
Related
I'm getting issue when I try to use < symbol with AND condition in sql query.
WHERE (latitude - 0.009 < AND latitude + 0.00 >)
AND (longitude - 0.009 <
AND longitude + 0.009 > )
Here is my code in CorePHP:
<?php
ini_set("display_errors", 0);
$lat = $_REQUEST['latit'];
$long = $_REQUEST['longit'];
include ("commanvar.php");
include ("class.db.php");
$coordinates_ = '';
// function to calculate distance between two latitudes and longitudes
function distance($lat1, $lng1, $lat2, $lng2, $miles = true)
{
$pi80 = M_PI / 180;
$lat1 *= $pi80;
$lng1 *= $pi80;
$lat2 *= $pi80;
$lng2 *= $pi80;
$r = 6372.797; // mean radius of Earth in km
$dlat = $lat2 - $lat1;
$dlng = $lng2 - $lng1;
$a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$km = $r * $c;
return ($miles ? $km * 0.621371192 : $km);
}
$obj = new db_connect();
// added by pramod
$sql = "SELECT name,
latitude,
longitude,
TYPE
FROM (SELECT name,
TO_BINARY_FLOAT(latitude) latitude,
TO_BINARY_FLOAT(longitude) longitude,
TYPE
FROM (SELECT name,
latitude,
longitude,
TYPE,
is_number (latitude) latisnum,
is_number (longitude) longisnum
FROM (SELECT name,
REGEXP_SUBSTR (latlon,
'[^,]+',
1,
1)
latitude,
REGEXP_SUBSTR (latlon,
'[^,]+',
1,
2)
longitude,
TYPE
FROM (SELECT olt.name,
olt_details.latlon,
'olt' AS TYPE
FROM ftth.olt, ftth.olt_details
WHERE olt_id = id
UNION
SELECT name, latlon, TYPE FROM ftth.splitters
))
WHERE latitude IS NOT NULL AND longitude IS NOT NULL)
WHERE latisnum = 1 AND longisnum = 1)
WHERE (latitude - 0.009 < $lat
AND latitude + 0.00 > $lat)
AND (longitude - 0.009 < $long
AND longitude + 0.009 > $long)";
//die();
$obj->db_query($sql);
// echo $sql;
// echo $lat . ',' . $long;
// define json array coordinates and prepare it's elements for returning via AJAX
$coordinates = '{
"coordinates": [';
while ($result = $obj->db_fetch_array(1)) {
$latitude = $result['LATITUDE'];
$longitude = $result['LONGITUDE'];
$name = $result['NAME'];
$type = $result['TYPE'];
$latlon_fiber = $result['LATITUDE'] . ", " . $result['LONGITUDE'];
$distance_fromswitch = distance($lat, $long, $latitude, $longitude, FALSE);
$distance_fromswitch = floor($distance_fromswitch * 1000);
$coordinates_ .= '{ "distance":"' . $distance_fromswitch . '" ,"site_name":"' . $name . '" , "latitude":"' . $latitude . '" , "longitude":"' . $longitude . '" , "device_type":"' . $type . '" },';
}
$coordinates .= rtrim($coordinates_, ',');
$coordinates .= "]}";
echo $coordinates;
$obj->free();
?>
I'm getting the following error due to this part < AND on line WHERE (latitude - 0.009 < AND latitude + 0.00 >)
ORA-00936: missing expression
00936. 00000 - "missing expression"
I think I've used some improper syntax while using < with AND on line WHERE (latitude - 0.009 < AND latitude + 0.00 >)
What can be the correction that need to be done here?
Think of it! The error message is self-explanatory.
You're trying to compare the result of subtraction to nothing. To correct this, you have to change it to:
WHERE (latitude - 0.009 < SomeValueHere AND latitude + 0.00 > SomeValueHere)
For further details, please see: ORA-00936 missing expression
[EDIT]
As to changes made in the question...
You're asking for help in debugging (inspect) your code. Let me quote the comment to your comment:
probably the variables do not have any values and passing empty
strings into your query.. – skybunk
Thank you, #skybunk!
I have MySQL table with some libraries. I need to make SQL query in PHP, which will select library by ID, and count distance. This is invalid query. Where I'm doing mistake in this query ?
$query = "SELECT *,
( 6371 *
acos(
cos(radians(" . $center_lat . ")) *
cos(radians(lat)) *
cos(radians(lng) - radians(" . $center_lng . ")) +
sin(radians(" . $center_lat . ") ) *
sin(radians( lat ) )
)
) AS distance
FROM `libraries`
WHERE id = ". $id ."
LIMIT 0 , 1";
Part of JSON string before decode: ,"avail":["Wed-2","Wed-3"]
decoded : $data = json_decode($return, true);
stored in variable : $avail = $data['avail'];
//array declarations
$days = array();
$cols = array();
Format above $avail:
if($avail != ""){
foreach($avail as $k=>$v)
{
echo $v;
$array = explode('-', $v);
$day =$array[0]; // Wed
$column = $array[1]; // 2
if($column == 1)
{
$col = "morning";
}
if($column == 2)
{
$col = "afternoon";
}
if($column == 3)
{
$col = "evening";
}
echo $col ."=>". $day;
array_push($cols,$col);
array_push($days,$day);
}
}
//Now use the array($days) to match values for column 'morning' in the posts table.
echo $sql=" SELECT * , (3956 * 2 * ASIN(SQRT( POWER(SIN(('$lat' - lat) * pi()/180 / 2), 2) +COS('$lat' * pi()/180) * COS(lat * pi()/180) * POWER(SIN(('$lon' - lon) * pi()/180 / 2), 2) ))) as distance
from posts,subjects WHERE posts.afternoon IN (" . implode(", ",$days) . ") AND posts.catID = '$catid' AND posts.subname LIKE '%$subject%' AND posts.subid = subjects.subid AND posts.catID = subjects.catid AND posts.pricing <= '$rate' having distance <= '$distance' order by distance ";
echo"<br/>";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$place=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$place[] = $row;
}
var_dump($place);
But it returned this error:
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Wed' in
'where clause'' in C:\wamp\www\fetch_tutor.php on line 128 ( ! )
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'Wed' in 'where clause' in C:\wamp\www\fetch_tutor.php on line 128
Based on this, I understood the array ($day) supplied is taken as field name. In fact that's the value in array to check in the 'morning' field in posts table.
How do I do that please.I've wasted almost a day on this!
It should be
WHERE posts.afternoon IN ('" . implode("',' ",$days) . "')
to get something like WHERE posts.afternoon IN ('Mon','Wed','Sun').
I'm trying to get a common database of geo points working with a radius search.
I've found several good tutorials on this topic, but I'm failing at the very end.
The main tutorial is here: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates.
The basic formula, in the form of an SQL query, is
SELECT * FROM Places
WHERE (Lat => 1.2393 AND Lat <= 1.5532) AND (Lon >= -1.8184 AND Lon <= 0.4221)
AND acos(sin(1.3963) * sin(Lat) + cos(1.3963) * cos(Lat) * cos(Lon - (-0.6981)))
<= 0.1570;
I've implemented this in a simple PHP test page like this:
$R = 6371; // radius of Earth in KM
$lat = '46.98025235521883'; // lat of center point
$lon = '-110.390625'; // longitude of center point
$distance = 1000; // radius in KM of the circle drawn
$rad = $distance / $R; // angular radius for query
$query = '';
// rough cut to exclude results that aren't close
$max_lat = $lat + rad2deg($rad/$R);
$min_lat = $lat - rad2deg($rad/$R);
$max_lon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));
$min_lon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));
// this part works just fine!
$query .= '(latitude > ' . $min_lat . ' AND latitude < ' . $max_lat . ')';
$query .= ' AND (longitude > ' . $min_lon . ' AND longitude < ' . $max_lon . ')';
// refining query -- this part returns no results
$query .= ' AND acos(sin('.$lat.') * sin(latitude) + cos('.$lat.') * cos(latitude) *
cos(longitude - ('.$lon.'))) <= '.$rad;
Am I missing something here? I think I'm following the methodology exactly, but I cannot get the "fine tuning" query to return any results.
not sure but :
$R = 6371; // radius of Earth in KM
$lat = '46.98025235521883'; // lat of center point
$lon = '-110.390625'; // longitude of center point
$distance = 1000; // radius in KM of the circle drawn
$rad = $distance / $R; // angular radius for query
$query = '';
// rough cut to exclude results that aren't close
$radR = rad2deg($rad/$R);
$max_lat = $lat + radR;
$min_lat = $lat - radR;
$radR = rad2deg($rad/$R/cos(deg2rad($lat)));
$max_lon = $lon + radR;
$min_lon = $lon - radR;
// this part works just fine!
$query .= '(latitude > ' . $min_lat . ' AND latitude < ' . $max_lat . ')';
$query .= ' AND (longitude > ' . $min_lon . ' AND longitude < ' . $max_lon . ')';
// refining query -- this part returns no results
$query .= ' AND acos(sin('.deg2rad($lat).') * sin(radians(latitude)) + cos('.deg2rad($lat).') * cos(radians(latitude)) *
cos(radians(longitude) - ('.deg2rad($lon).'))) <= '.$rad;
I am having a serious problem converting my 'select' statement into something that will work with the zend paginator... could someone have a crack at it, as I am having no luck...
Here is my query:
$query = "SELECT
user_id, name, gender, city, province, country, image_id, one_liner, self_description, reputation
FROM
users
WHERE
(
(69.1 * (latitude - " . $user->latitude . ")) *
(69.1 * (latitude - " . $user->latitude . "))
) + (
(69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) *
(69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3))
) < " . pow($radius, 2) . "
ORDER BY
(
(69.1 * (latitude - " . $user->latitude . ")) *
(69.1 * (latitude - " . $user->latitude . "))
) + (
(69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) *
(69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3))
Here is what I have so far:
$select = $db->select();
$select->from(
array('users'),
array(
'user_id',
'name',
'gender',
'city',
'province',
'country',
'image_id',
'one_liner',
'self_description',
'reputation'
)
);
$select->where("(69.1 * (latitude - " . $user->latitude . ")) * (69.1 * (latitude - " . $user->latitude . "))) + ((69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) * (69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3))) < " . pow($radius, 2));
$select->order("(69.1 * (latitude - " . $user->latitude . ")) * (69.1 * (latitude - " . $user->latitude . "))) + ((69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) * (69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3))) ASC");
Why do you have "<" in your order by clause?
What does this have to do with Zend_Paginator? Ah, do you have the query and you don't know how to make a paginator with it, or is the paginator not working with this query?
The only thing I can see is you're missing an opening parenthesis in both the where() and order() clause:
$select->where("((69.1 * [...] ");
$select->order("((69.1 * [...] ");
^
So maybe Zend_Paginator isn't working because the SQL query has errors?
And of course I have to ask: are those variables you're interpolating safe, or should you really be using $db->quote($user->latitude, Zend_Db::FLOAT_TYPE)?
Assuming you are using MVC-pattern, won't this work?
in your bootstrap:
Zend_View_Helper_PaginationControl::setDefaultViewPartial('pagination.phtml');
in your controller:
$page = Zend_Paginator::factory($select);
$page->setCurrentPageNumber($this->_getParam('page', 1));
$page->setItemCountPerPage($this->_getParam('par', 20));
$this->view->results= $page;
in your view:
<?php foreach($this->results as $result) : ?>
<!-- print some $result stuff here -->
<?php endforeach;?>
<?= $this->results ?>
then place a pagination.phtml example that you can find on zend manual
-Lo