PHP - Showing Number Of Items With Distance
I have a page that gets the closest stores to a latitude and longitude. I want to have a MySQL table like this:
location_id:::::items showing how many items are at each store and then show 'spit' them in the following format with the lowest number of items first: location_id, distance to location_id, items. here is the code I am using to show location_id by distance Code: [Select] <?php include "connectionfile.php"; $lat = $_GET["lat"]; $lng = $_GET["lng"]; $sql = mysql_query("SELECT id, ( 6371 * acos( cos( radians($lat) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < 250 ORDER BY distance LIMIT 0 , 60; "); WHILE($lstlocations = mysql_fetch_array($sql)) { $location_id[$count]=$lstlocations['id']; $distance=$lstlocations['distance']; echo "id = " . $location_id[$count] . " Distance = " . $distance. "<br>"; $count = $count + 1; } ?> What would be the best way to achieve this? Similar TutorialsI'm new at PHP and have a problem. I have a MySql database with lists of students grouped into classrooms. A typical group is shown in the attached screenshot screenshot.docx. I want to be able to select one or more of the names by using the associated checkbox, and upgrade a student or students into a different group as defined in the radio button list also in the screenshot. I have the rudiments of the file attached, but I have absolutely no idea how I can post the array so that the records are updated. Each student has an individual record with a field name userGroup which holds a string nominated by their classroom teacher, such as "year7", "year 8" and so on while they are in one of the several classrooms, but when they leave school this is recorded in a field named noGroup with a value of 0 or 1. I can post further details as required, but it would be great if someone could help me. I have a problem that occurred only recently, apparently by some change my webhost made on the server. Some time ago I wrote a script that simulates a Poedit-type editor. The script has about 1500 textareas (the translation fields) with unique names, dynamically generated. All worked fine. Now suddenly I get errors (see below) when I use more than 1000 textareas. It is not a problem of $_POST size, if happens also with empty textareas. I will show here a simple php test file that I called testta.php, which creates the same error as my much more complicated real script: Code: [Select] <?php if(isset($_POST['test'])) { echo 'The textareas were posted successfully!<br>'; } $max = 1500; echo '<form action="testta.php" method="POST">'; echo '<input type="submit" name="test" value="Submit"><br>'; for($i=0; $i < $max; $i++) { echo '<textarea name="test'.$i.'">name is test'.$i.'</textarea><br>'; } echo '</form>'; ?> The error message generated in the browser: 500 Server Error: A misconfiguration on the server caused a hiccup. Check the server logs, fix the problem, then try again. From the Apache log file: [Sat Apr 28 12:47:48 2012] [error] [client 93.172.175.50] Premature end of script headers: testta.php, referer: http://****/*****/testta.php (stars added for privacy) When $max is set to a number < 1000 it works. On the web I have only found answers that deal with max size of posts, but as I mentioned that is not my case. My webhost can't help me out either. Until last Friday all worked fine. Does anyone know what server setting could create this problem? Thanks in advance, Kathy This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=334480.0 Hi everyone, Like the title says I need to count the amount of 1's in a column but I can't figure out how. Gr and thanx already Ryflex I'm getting the dreaded " Invalid parameter number: number of bound variables does not match number of tokens" error and I've looked at this for days. Here is what my table looks like:
| id | int(4) | NO | PRI | NULL | auto_increment | | user_id | int(4) | NO | | NULL | | | recipient | varchar(30) | NO | | NULL | | | subject | varchar(25) | YES | | NULL | | | cc_email | varchar(30) | YES | | NULL | | | reply | varchar(20) | YES | | NULL | | | location | varchar(50) | YES | | NULL | | | stationery | varchar(40) | YES | | NULL | | | ink_color | varchar(12) | YES | | NULL | | | fontchosen | varchar(30) | YES | | NULL | | | message | varchar(500) | NO | | NULL | | | attachment | varchar(40) | YES | | NULL | | | messageDate | datetime | YES | | NULL |Here are my params: $params = array( ':user_id' => $userid, ':recipient' => $this->message_vars['recipient'], ':subject' => $this->message_vars['subject'], ':cc_email' => $this->message_vars['cc_email'], ':reply' => $this->message_vars['reply'], ':location' => $this->message_vars['location'], ':stationery' => $this->message_vars['stationery'], ':ink_color' => $this->message_vars['ink_color'], ':fontchosen' => $this->message_vars['fontchosen'], ':message' => $messageInput, ':attachment' => $this->message_vars['attachment'], ':messageDate' => $date );Here is my sql: $sql = "INSERT INTO messages (user_id,recipient, subject, cc_email, reply, location,stationery, ink_color, fontchosen, message,attachment) VALUES( $userid, :recipient, :subject, :cc_email, :reply, :location, :stationery, :ink_color, :fontchosen, $messageInput, :attachment, $date);"; And lastly, here is how I am calling it: $dbh = parent::$dbh; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); if (empty($dbh)) return false; $stmt = $dbh->prepare($sql); $stmt->execute($params) or die(print_r($stmt->errorInfo(), true)); if (!$stmt) { print_r($dbh->errorInfo()); }I know my userid is valid and and the date is set above (I've echo'd these out to make sure). Since the id is auto_increment, I do not put that in my sql (though I've tried that too), nor in my params (tried that too). What am I missing? I feel certain it is something small, but I have spent days checking commas, semi-colons and spelling. Can anyone see what I'm doing wrong? I have a webpage where all the database items are displyes in a table format.The table also has a check box.Upon clicking the delete button i need to delete all the items whish has the checkbox checked. How will i do that How do I show how many miles away the nearest location is? This code works with showing stores within the radius of the zip code entered, but it does not show the miles. Can anybody see what I have to do to display the miles? Code: [Select] <?php // Create page variables $r = NULL; $z = NULL; $stores = NULL; $Errors = NULL; include('inc/connect.db.mrk.php'); // Declare page functions function Dist($lat1, $lon1, $lat2, $lon2) { $distance = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon1 - $lon2)); $distance = (rad2deg(acos($distance))) * 69.09; return $distance; } ### Handle form if submitted if (isset ($_POST['submitted'])) { // Validate Postcode code field if (!empty ($_POST['zip']) && is_numeric ($_POST['zip'])) { $z = (int)$_POST['zip']; // Verify Postcode code exists $query = "SELECT latitude, longitude FROM zipdata WHERE zip = '$z'"; //$result = mysql_query ($query); $result=mysql_query($query) or die ('Invalid query.'); if (mysql_num_rows ($result) == 1) { $zip = mysql_fetch_assoc ($result); } else { $Errors = '<p>The postcode code you entered was not found!</p>'; $z=NULL; } } // Validate radius field if (isset ($_POST['radius']) && is_numeric ($_POST['radius'])) { $r = (int)$_POST['radius']; } // Proceed if no errors were found if ($r && $z) { // Retrieve coordinates of the locations $result = mysql_query("SELECT LocAddState, MktName, LocAddSt, LocAddZip, LocAddCity, x1, y1 FROM store INNER JOIN zipdata ON store.LocAddZip=zipdata.zip") or die(mysql_error()); //$result = mysql_query ($query); // Go through and check all locations while ($row = mysql_fetch_assoc ($result)) { // Separate closest locations $distance = Dist($row['y1'], $row['x1'], $zip['latitude'], $zip['longitude']); // Check if store is in radius if ($distance <= $r) { $stores[] = array ( 'name' => $row['MktName'], 'address' => $row['LocAddSt'], 'state' => $row['LocAddState'], 'town' => $row['LocAddCity'], 'postal' => $row['LocAddZip'], ); } } } else { $Errors = ($Errors) ? $Errors : '<p>Errors were found please try again!</p>'; } } ?><html> <head> <title>Store Locator</title> </head> <body> <form action="" method="post"> <p>Enter your zip code below to find locations near you.</p> <?php echo ($Errors) ? $Errors : ''; ?> <div> <label>Zip:</label> <input name="zip" type="text" size="10" maxlength="5" /> </div> <div> <label>Search Area:</label> <select name="radius" id="radius"> <option value="5">5 mi.</option> <option value="10">10 mi.</option> <option value="15">15 mi.</option> <option value="20">20 mi.</option> <option value="50">50 mi.</option> <option value="100">100 mi.</option> </select> </div> <div> <input type="hidden" name="submitted" value="submitted" /> <input type="submit" value="Submit" /> </div> </form> <?php if (isset ($stores)) { if (!empty ($stores)) { echo '<p><strong>' . count ($stores) . ' results were found.</strong></p>'; foreach ($stores as $value) { echo '<p><strong>' . $value['name'] . '</strong><br />'; echo $value['address'] . '<br />'; echo $value['town'] . ', ' . $value['state'] . ' ' . $value['postal'].'<br />'; echo $distance . ' miles away <br />'; /*echo ' <a target="_blank" href="http://maps.google.com/maps?q=', $value['address'], ' ', $value['town'], ', ', $value['state'], ' ', $value['postal'], '">Map this location</a><br />'; */ echo '</p>'; } } else { echo '<p><strong>No results found</strong></p>'; } } ?> </body> </html> Right now it shows like this Code: [Select] 1482.92070414 miles away Thanks in advance Hi all, Using a form with check boxes divided into different categories, I collect data selected by the user. I now want to combine each choice in each category with each choice in the other categories and list the combinations to the user. If the user chooses one or more options in each category, it is relatively easy to nest foreach loops, since the number of categories will always be the same. For example, if the form contains three categories of options, the code will be: Code: [Select] foreach ($form['cat_1'] as $k1 => $val1) { foreach ($form['cat_2'] as $k2 => $val2) { foreach ($form['cat_3'] as $k3 => $val3) { echo $val1.' _ '.$val2.' _ '.$val3.'<br/>'; } } } Things get complicated if the user does not select options within a given category. More generally, I want to be able to generate the list regardless of the number of categories in which the user selects options. Thank you in advance for your advice.
Hi,
Write a function that calculates the Euclidean distance for points: eucl(q1,z1,r2,z2). Date:
$r1=1; $z1=12; $r1=43; $z1=123;
formula to the Euclidean distance: (r1,z1,r2,z2)=sqrt[(r1-z1)*(r1-z1) + (r2-z2)*(r2-z2)],
Can anyone help?
I made a post a while back about this topic he 1. The input from the project will be coming from a mobile app which will be using a qr code. The qr code contains the Room Number and the 2 Access Points for each room. When a user scans the qr code it will pass that info to the web app that has the algorithm and verify what room he/she is in the access point that was 'scanned'. 2. For the testing of the project we decided to use two rooms of the building of our alma mater and the access points were already defined based on tests:
Room 413 has Access Point 1 that have the values of -67 dBm to -89 dBm and Access Point 2 that have the values of -40 dbm to -57 dBm while
3. I already inputted the values and the rooms I've mentioned above in mysql to verify if the input from the qr code that was scanned it correct. but sadly we are stuck with the algorithm itself.
This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=348500.0 Hi Guys I need a PHP function to which I pass two postcodes and it works out the road distance, I dont mind using google or any other API I have managed to fing JS ways and php functions using crow route but I really really need a traffic distance in PHP Please advice, Help Thank you Table Of Contents - General Description - Database Image - Code - Code - Issue I have the following code (from outside sources), which, is apparently incompatible with my co-ordinate types. Here is a database excerpt (first thirty rows) of about 9200 airports from around the world. <?php function distance($lat1, $lon1, $lat2, $lon2, $unit) { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; $unit = strtoupper($unit); if ($unit == "K") { return ($miles * 1.609344); } else if ($unit == "N") { return ($miles * 0.8684); } else { return $miles; } } $dep = $_GET['dep']; $arr = $_GET['arr']; $sql = 'SELECT * FROM `airports` WHERE `iata` = \'' . $dep . '\''; $query = mysql_query($sql); $dep = mysql_fetch_array($query); $sql = 'SELECT * FROM `airports` WHERE `iata` = \'' . $arr . '\''; $query = mysql_query($sql); $arr = mysql_fetch_array($query); echo distance($dep['latt'], $dep['long'], $arr['latt'], $arr['latt'], "k") . " km<br>"; ?> Here is my output [dep=yyz, arr=yul] with [yyz = 43.68, -79.63; yul = 45.47, -73.74] : 8719.64724823 km Obviously, with YYZ being Toronto, Canada and YUL being Montreal, Canada, it is definitely not 9000 km away (actually, ~500 km). Can you help me convert the units, or re-write the algorithms in order to make it function correctly. Thank you in advance. Getting the difference in seconds between two timestamps is easy. Taking the seconds and doing a breakdown of time frames is also easy. Code: [Select] <?php echo '<p>There are a total of ' . round($seconds) . ' seconds between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round($seconds / 60) . ' minutes between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round(($seconds / 60) / 1440) . ' days between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round((($seconds / 60) / 1440) / 7) . ' weeks between Timestamp 1 and Timestamp 2.</p>'; echo '<p>There are a total of ' . round((((($seconds / 60) / 1440) / 7) / 30)) . ' months between Timestamp 1 and Timestamp 2.</p>'; echo '<p>The total breakdown of time from Timestamp 1 to Timestamp 2 is .</p>'; ?> What I am trying to figure out, is get a collective amount as well.... X years X months X weeks X days X minutes and X seconds. Does anyone have any good algorithm for handling that, or have any feedback on where to start to handle this type of math. Hi, I have been using the following function on my server and it works fine but when I try and use it on a different server it wont seem to work. Any ideas on why it wont work on the new server and any ideas on how I can do some error checking to figure out why ? Thanks in advance, Scott Code: [Select] <?php function get_driving_information($start, $finish, $raw = false) { # Convert any lon / lat coordingates if(preg_match('@-?[0-9]+\.?[0-9]*\s*,\s*-?[0-9]+\.?[0-9]@', $start)) { $url = 'http://maps.google.co.uk/m/local?q='.urlencode($start); if($data = file_get_contents($url)) { if(preg_match('@<div class="cpfxql"><a href="[^"]*defaultloc=(.*?)&ll=@smi', $data, $found)) { $start = trim(urldecode($found[1])); } else { throw new Exception('Start lon / lat coord conversion failed'); } } else { throw new Exception('Start lon / lat coord conversion failed'); } } if(preg_match('@-?[0-9]+\.?[0-9]*\s*,\s*-?[0-9]+\.?[0-9]@', $finish)) { $url = 'http://maps.google.co.uk/m/local?q='.urlencode($finish); if($data = file_get_contents($url)) { if(preg_match('@<div class="cpfxql"><a href="[^"]*defaultloc=(.*?)&ll=@smi', $data, $found)) { $finish = trim(urldecode($found[1])); } else { throw new Exception('Finish lon / lat coord conversion failed'); } } else { throw new Exception('Finish lon / lat coord conversion failed'); } } if(strcmp($start, $finish) == 0) { $time = 0; if($raw) { $time .= ' seconds'; } return array('distance' => 0, 'time' => $time); } $start = urlencode($start); $finish = urlencode($finish); $distance = 'unknown'; $time = 'unknown'; $url = 'http://maps.google.co.uk/m/directions?saddr='.$start.'&daddr='.$finish.'&hl=en&oi=nojs&dirflg=d'; if($data = file_get_contents($url)) { if(preg_match('@<span[^>]+>([^<]+) (mi|km)</span>@smi', $data, $found)) { $distanceNum = trim($found[1]); $distanceUnit = trim($found[2]); if($raw) { $distance = $distanceNum.' '.$distanceUnit; } else { $distance = number_format($distanceNum, 2); if(strcmp($distanceUnit, 'km') == 0) { $distance = $distanceNum / 1.609344; } } } else { throw new Exception('Could not find that route'); } if(preg_match('@<b>([^<]*)</b>@smi', $data, $found)) { $timeRaw = trim($found[1]); if($raw) { $time = $timeRaw; } else { $time = 0; $parts = preg_split('@days?@i', $timeRaw); if(count($parts) > 1) { $time += (86400 * $parts[0]); $timeRaw = $parts[1]; } $parts = preg_split('@hours?@i', $timeRaw); if(count($parts) > 1) { $time += (3600 * $parts[0]); $timeRaw = $parts[1]; } $time += (60 * (int)$timeRaw); } } return array('distance' => $distance, 'time' => $time); } else { throw new Exception('Could not resolve URL'); } } I have this script that works 9/10 of how it's suppose too. This does not calculate the correct distance for the results. Can anybody see where the problem lies? Here is the code Code: [Select] // see if our zip code has been posted, and if it is a 5 digit # if (isset($_POST['zip'])) { // remember to sanitize your inputs // this removes whitespace around the data and the next line makes sure its a 5 digit number $findzip = trim($_POST['zip']); if (preg_match("#^\d{5}$#",$findzip)) { include('inc/connect.php'); include('inc/functions.php'); // create a query that will select the zip code (if we can't find the user entered zip, we return an error) $query = "SELECT latitude,longitude,state,city FROM zipdata WHERE zip=".$findzip." LIMIT 1"; $result = mysql_query($query); if (mysql_num_rows($result) > 0) { // grab the latitude, longitude,state and city from our result list($flat,$flon,$fstate,$fcity) = mysql_fetch_row($result); // now get all markets in the same state, or all markets if no states match // we want to reduce the amount of work the database has to do so we see if a state matches $query = "SELECT * FROM mrk WHERE state='".$fstate."'"; $result = mysql_query($query); if (mysql_num_rows($result) < 1) { $query = "SELECT * FROM mrk"; $result = mysql_query($query); } // now we process the markets to gather their data, //this result should not be empty, so I was lazy and didn't write an else case if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_assoc($result)) { // first put all of the data for this market into an array, with the market id as the key $storeinfo[$row['id']] = $row; // get the store zip $dzip = $row['zip']; // query for the store's latitude and longitude $query = "SELECT latitude,longitude FROM zipdata WHERE zip=".$dzip." LIMIT 1"; $result2 = mysql_query($query); if (mysql_num_rows($result2) > 0) { list($dlat,$dlon) = mysql_fetch_row($result2); // now get the distance from the user entered zip $stores[$row['id']] = calcDist($flat,$flon,$dlat,$dlon); } } } asort($stores); print "<p>The Markets closest to you: $findzip</p><br>\n"; $maploc = "'You are here','$findzip',"; foreach($stores as $k=>$v) { $output .= "<h3 style='margin:0;padding:0'><b>".$storeinfo[$k]['company']."</b><br>(approx ".round($v)." miles)</h3>"; $output .= "<p style='margin:0 0 10px 0;padding:0'><a href='".$storeinfo[$k]['url']."'>".$storeinfo[$k]['url']."</a><br>"; $output .= $storeinfo[$k]['city']." ".$storeinfo[$k]['state'].", ".$storeinfo[$k]['zip']."</p>"; } echo $output; } } } Here is the function.php Code: [Select] function calcDist($flat, $flon, $dlat, $dlon) { $distance = sin(deg2rad($flat)) * sin(deg2rad($dlat)) + cos(deg2rad($flat)) * cos(deg2rad($dlat)) * cos(deg2rad($flon - $dlon)); $distance = (rad2deg(acos($distance))) * 69.09; return $distance; } Thank you in advance Hi i am looping through some history data i have collected via soap. i have the data in an array containing lat, lon and timestamp. Code: [Select] foreach($history['data'] as $record) { echo 'add(jQuery(this), number += 1, "' . date("d-m-Y @ h:i:s",$record['timestamp']) . '", "map_post.php?n=' . $name . 'u=' . $history['user'] . '", "' . $history['user'] . '", "' . $record['latitude'] . '", "' . $record['longitude'] . '");'; } i wondered it it would be possible to check if each position is within say 300 metres of the last position and if so dont display it? Hello,
I have problem durring binding update query. I can't find what is causing problem.
public function Update(Entry $e) { try { $query = "update entry set string = $e->string,delimiter=$e->delimiter where entryid= $e->id"; $stmt = $this->db->mysqli->prepare($query); $stmt->bind_param('ssi',$e->string,$e->delimiter,$e->id); $stmt->close(); } catch(Exception $ex) { print 'Error: ' .$ex->getMessage(); } }When I run function update I'm getting next error:Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement Can you help me to solve this problem ? Edited by danchi, 17 October 2014 - 10:25 AM. I need to display a number(the number is retrieved from the db) in the form input field such that only the last 4 digits is visbile, the remaining can be masked as * or X or whatever is applicable. I know the last 4 can be obtained as follows: Code: [Select] $number=substr($number,-4,4); But when i hit the submit button the form validates the input field and checks if the number is a valid number of a specific format. Therefore when I click on the submit button then I should still be able to unmask the masked numbers or do something similar that would help me validate the whole number. Code: [Select] <input type="text" name="no" value="<?php if(!empty($number)){ echo $number;} ?>"> I am pretty new to PHP and am trying to create a simple (so I assumed) page to takes data from one html page(works fine) and updates a MYSQL Database. I am getting no error message, but the connect string down to the end of the body section is showing up as plain text in my browser window. I do not know how to correct this. I have tried using two different types of connect strings and have verified my names from the HTML page are the same as listed within the php page. Suggestions on what I need to look for to correct would be great. I have looked online, but so far all I am getting is how to connect, or how to create a comment, so I thought I would try here. Thank you for any assistance I may get!! - Amy - Code: [Select] <body><font color="006600"> <div style="background-color:#f9f9dd;"> <fieldset> <h1>Asset Entry Results</h1> <?php // create short variable names $tag=$_POST['tag']; $serial=$_POST['serial']; $category=$_POST['category']; $status=$_POST['status']; $branch=$_POST['branch']; $comments=$_POST['comments']; if (!$tag || !$serial || !$category || !$status || !$branch) { echo "You have not entered all the required details.<br />" ."Please go back and try again."; exit; } if (!get_magic_quotes_gpc()) { $tag = addslashes($tag); $serial = addslashes($serial); $category = addslashes($category); $status = addslashes($status); $branch = addslashes($branch); $comments = addslashes($comments); } //@ $db = new mysqli('localhost', 'id', 'pw', 'inventory'); $db = DBI->connect("dbi:mysql:inventory:localhost","id","pw") or die("couldnt connect to database"); $query = "insert into assets values ('".$serial."', '".$tag."', '".$branch."', '".$status."', '".$category."', '".$comments."')"; $result = $db->query($query); if ($result) { echo $db->affected_rows." asset inserted into Inventory."; } else { echo "An error has occurred. The item was not added."; } $db->close(); ?> </fieldset> </div> </body> |