mysqli_num_rows() expects parameter 1 to be mysqli_result geolocation - php

I really don't know what i'm doing wrong. I want to count the rows in my query. My id's started from 1 to ... step 1, so the biggest number is the last record. I only want to let the script run on the last record of de DB. So here is my code.
public function saveLongLan()
{
define("MAPS_HOST", "maps.google.com");
define("KEY", "MYKEY");
$link = mysql_connect('localhost', 'root', 'root');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db('Foodsquare', $link);
if (!$db_selected)
{
die("Can\'t use db : " . mysql_error());
}
$query = "SELECT * FROM tblPlaces WHERE 1";
$result = mysql_query($query);
$row_cnt = mysqli_num_rows($result);
if (!$result)
{
die("Invalid query: " . mysql_error());
}
$delay = 0;
$base_url = "http://" . MAPS_HOST . "/maps/geo?output=xml" . "&key=" . KEY;
while ($row = #mysql_fetch_assoc($result))
{
$geocode_pending = true;
while ($geocode_pending)
{
$address = $row["Street"];
$id = $row["Id"];
$request_url = $base_url . "&q=" . urlencode($address);
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0)
{
// Successful geocode
$geocode_pending = false;
$coordinates = $xml->Response->Placemark->Point->coordinates;
//explode functie breekt een string af vanaf een bepaald teken en stopt hem dan in een array
$coordinatesSplit = explode(',', $coordinates);
// formaat: Longitude, Latitude, Altitude
$lat = $coordinatesSplit[1];//getal = plaats in array
$lng = $coordinatesSplit[0];
$query = sprintf("UPDATE tblPlaces " .
" SET lat = '%s', lng = '%s' " .
" WHERE id = '". $row_cnt . "' LIMIT 1;",
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
if (!$update_result)
{
die("Invalid query: " . mysql_error());
}
} else if (strcmp($status, "620") == 0)
{
// sent geocodes too fast
$delay += 100000;
}
else
{
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocoded. ";
echo "Received status " . $status . " \n";
}
usleep($delay);
}
}
}

your query is incorrect $query = "SELECT * FROM tblPlaces WHERE 1";
you should specify the column name after where clause for comparison with a value for example: WHERE column_name = 1 or something like that.

You're using mysqli_num_rows($result) but you aren't using MySQLi.
Change:
$row_cnt = mysqli_num_rows($result);
To:
$row_cnt = mysql_num_rows($result);
And you should be good to go.

Related

PHP Fatal error: Could not queue new timer in Unknown on line 0

I write a simple web application for my compnay that can let user log in to arrange their work time. Besides, user can also view the report of he's or she's attandence that I use ajax to callback from java.jar. (We use java to analyze)I use Xampp to set up the server in virtual machine HyperV and it can run successfully at the begining but after twenty hours or more than one day it won't let anyone to log in.
I open the error.log shows that :
PHP Fatal error: Could not queue new timer in Unknown on line 0
. . . and than:
PHP Warning: mysqli_connect(): (HY000/2002): Unknown Error
I don't understand what can cause that happend and how to solve it.
I alreday know is when I restarted the apache server, it can still be used till that error happened.
My System Enviroment :
win7 64 bit HyperV
xampp Apache/2.4.18, php/7.0.6, mysql/ 5.1
Here is my code:
mysql_start.php
<?php
header("Content-Type:html;charset=utf-8");
$servername = "127.0.0.1";
$username = "root";
$password = "cc1234";
$dbname = "cc_tw000427";
$conn = null;
try {
$conn = new mysqli($servername, $username, $password, $dbname);
} catch (Exception $e) {
$error_message = "Connect Error (" .$conn->connect_errno ." )" . $conn->connect_error;
error_log($error_message, 3, "php_error_log");
header("location:login.php?err=$e");
}
$conn->set_charset("utf-8");
$strDBColLoingAccount = "AccountID";
checklogin.php
session_start();
include_once("mysql_start.php");
$yid = trim(filter_input(INPUT_POST, "yid"));
$passd = trim(filter_input(INPUT_POST,"passd"));
$strSql = "SELECT acc.*, b.String_10_1 FROM basicstoreinfomanageacc_sub acc,basicstoreinfo b
WHERE acc.$strDBColLoingAccount ='$yid' AND acc.String_50_1 = b.String_50_1";
$result = $conn->query($strSql);
$n = $result->num_rows;
if ($n == 0) {
header("Location:../desktop/login.php?err=1");
echo "Error 1";
exit();
}
while ($row = $result->fetch_assoc()) {
$passd_right = $row["AccountPwd"];
$user_id = $row["AccountID"];
$user_name = $row["AccountName"];
$user_dep_id = $row["String_10_1"];
$user_dep = $row['String_50_1'];
}
$result->close();
if (($passd_right == "") || ($passd_right == NULL)){
session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = $user_name;
header("location:newpwd.php");
exit();
}
if ($passd == $passd_right) {
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = $user_name;
$_SESSION['loginOK'] = 'yes';
$_SESSION['year_i'] = date('Y',time());
$_SESSION['year_f'] = date('Y',time());
$_SESSION['month_i'] = date('m',time());
$_SESSION['month_f'] = date('m',time());
$_SESSION['day_i'] = date('d',time());
$_SESSION['day_f'] = date('d',time());
$_SESSION['Hour'] = date('Y-m-d G:i:s',strtotime('+6 hour'));
$_SESSION['user_dep_id'] = $user_dep_id;
$_SESSION['user_dep'] = $user_dep;
header("Location:../desktop/Punch.php");
} else {
header("Location:../desktop/login.php?err=1");
}
$conn->close();
?>
Next two *.php files are used to receive the post from the web.
The select.php is used to select the data from mysql than output in html tag.
The save.php is used to save the data post from web.
select.php
<?php
session_start();
include_once '../control/mysql_start.php';
$strYear = $_POST['year'];
$strMonth = $_POST['month'];
$strDay = $_POST['day'];
.
.//some codes
.
$strSql = "SELECT * FROM basicemploymentinfo bei WHERE bei.BelongStore = '". $_SESSION['user_dep']."'".
"AND ((bei.datetime_2 is null AND bei.datetime_3 is null) OR (bei.datetime_2 is null AND bei.datetime_3 >= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d'))" .
" OR (bei.datetime_2 <= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d') AND bei.datetime_3 is null)" .
" OR (bei.datetime_2 <= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d') AND bei.datetime_3 >= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d'))) "
."AND bei.Active ='Y'";
$EmpId = array();
$EmpName = array();
if ($result = $conn->query($strSql)) {
while($row = $result->fetch_assoc()) {
array_push($EmpId, $row['String_20_1']);
array_push($EmpName, $row['String_20_2']);
.
.//some codes
.
}
}
$Emp = array_combine($EmpId, $EmpName);
$strSql = " SELECT Distinct date_format(DateTime_1, '%e') as date, AutoCheck
FROM hrotcheck
WHERE date_format(DateTime_1, '%Y-%m-%d') = '$newformat'
AND AutoCheck = 'C'
AND String_20_1 IN ($array_emp_id)";
if ($result = $conn->query($strSql)) {
$n = $result->num_rows;
if ($n > 0) { $checkboxVerify = 'C';}
}
$result->close();
foreach ($Emp as $EId => $EName)
{
.
.//some codes
.
$strSql = "SELECT RegularM_1, RegularM_2, FORMAT(OT_3, 1) as OT_3, TOM, TOTM, Notes, AutoCheck FROM hrotcheck where string_20_1 = '" . $EId . "' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$newformat'";
$result = $conn->query($strSql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$RegularM_1 = $row['RegularM_1'];
$RegularM_2 = $row['RegularM_2'];
$OT3 = $row['OT_3'];
$tom = $row['TOM'];
$totm = $row['TOTM'];
$notes = $row['Notes'];
}
}
$result->close();
.
.//I did a lot of SQL select and use that to create htmltable
.
$output .= '
<tr data-table="sub">
<td>'.$row['string_20_1'].'</td>
<td>'.$row['string_20_2'].'</td>
.
.//<td>...</td>
.
<td class="'.$condition16.'">'.$notes.'</td>
<td class="'.$condition17.'"></td>
</tr>
';
}
.
.//some codes
.
$strSql01 = "SELECT * FROM manufacturejobschedulingpersonal where string_20_1 = '".
$row['string_20_1']."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$newformat'";
$result01 = $conn->query($strSql01);
if ($result01->num_rows > 0) {
while ($row01 = $result01->fetch_assoc()) {
.
.//some codes
.
}
}
$result01->close();
.
.//some codes
.
$result->close();
$conn->close();
echo $optionUse.'?'.$checkboxVerify.'?'.$output.'?'.$hasCheckDate;
?>
save.php
<?php
session_start();
include_once '../control/mysql_start.php';
$arrayObjs = $_POST;
.
.//some codes
.
$msDanger = '';
foreach($arrayObjs as $array)
{
foreach($array as $row)
{
$UserId = $row['UserId'];
$UserName = $row['UserName'];
.
.//some codes
.
$strSql = "SELECT * FROM manufacturejobschedulingpersonal where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
$result = $conn->query($strSql);
if( $result->num_rows > 0) {
if ($table == 'main') {
$strSql = "Update manufacturejobschedulingpersonal SET String_10_1 ='$String_10_1', String_Assist01 ='$assist_1',String_Assist02='$assist_2' where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
} else {
$strSql = "Update manufacturejobschedulingpersonal SET String_10_1 ='$String_10_1' where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
}
$result = $conn->query($strSql);
} else {
$strSql = "INSERT INTO manufacturejobschedulingpersonal (string_20_1,string_20_2,YM,DateTime_1,String_10_1,String_Assist01,String_Assist02)".
"VALUES ( '$UserId', '$UserName', '$YM', '$DateTime_1', '$String_10_1','$assist_1','$assist_2')";
$result = $conn->query($strSql);
}
.
.//A lot of sql CRUD
.
}
}
$conn->close();
$last_line = exec('java -jar C:/CCERP/ChainCodeERP/ExtraModule/HRMultiOTCheck/HRMultiOTCheck.jar -ssa '.$javaDate.' ' .$javaDepId, $return_var);
echo 'Updated';
?>

SQL Connection creates excessive concurrent HTTP connections to the host

I kept commenting parts of my PHP script till this is what I ended up with. This thing creates about 200 to 300 concurrent connections in under a minute to the SQL ip (checked from the gateway) and I don't understand why.
Shouldn't closing the SQL connection end the communication between the servers?
The php script is being called once a second via JavaScript, I'm the only user on the website.
PHP implementation of the sock (taken from the net, fclose() added as that's how I read socks are closed)
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM `users`");
$num_rows = mysqli_num_rows($result);
$result = mysqli_query($con,"SELECT * FROM `users` WHERE admlevel>0");
$num_admrows = mysqli_num_rows($result);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM jbchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$jbchat = $jbchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM frchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$frchat = $frchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM drchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$drchat = $drchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM cschat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$cschat = $cschat . $data[$i] . "<br>";
}
$today = getdate();
$date = $today['mday'] . "/" . $today['mon'] . "/" . $today['year'];
if($today['minutes']>9)
$time = $today['hours'] . ":" . $today['minutes'];
else
$time = $today['hours'] . ":0" . $today['minutes'];
$sqlx = 'SELECT * FROM notifications WHERE username=? ORDER BY id DESC LIMIT 5';
# Prepare statement
$stmt = $con->prepare($sqlx);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sqlx . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_assoc())
{
if($row['read']==0)
$nnumber = $nnumber+1;
$notifications = $notifications . "
<li>
<a href=\"#\" onclick=\"invisphp2('http://r4ge.ro/php/readnotif.php?notifid=" . $row['id'] . "')\">
<i class=\"fa fa-warning danger\"></i>" . $row['text'] . "
<br>" . $row['date'] . "
</a>
</li>";
}
$result = mysqli_query($con,"SELECT * FROM chat ORDER BY id DESC LIMIT 30");
$data = array();
$i=1;
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['name'] . ": " . $row['msg'];
$i=$i+1;
}
for($i=30;$i>0;--$i)
{
$lchat = $lchat . $data[$i] . "<br>";
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
Edit: after listening to a comment that's now deleted, I removed every single query except the first one, so this code is now being ran, the connections still rocketed to 150 in 20-30 seconds.
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
I know this will make me look very bad.
Unfortunately there is nothing bad in this particular code.
The problem was at a much deeper level in the site's framework, and the above code being the homepage, lead me to think it was the source of the problem.
To #developerwjk , the answer is no, combining procedural and object oriented implementations has no effect whatsoever on the functionality of mysqli, it works great.
The culprit: lack of mysqli_close() at the end of every single PHP that creates a connection
Don't trust the documentation when it says the connection is closed on script end, put it there just to be safe.

Why is my PHP / MySQL inserting instead of updating?

if ($Funct == "BUILD" AND $Mode == "GROUND")
{
$sql = "SELECT * FROM $landCon WHERE North = '" . $North . "' AND West = '" . $West ."'" ;
$result = mysql_query($sql) or die("Error occurred in [$sql]: " . mysql_error());
$count = mysql_num_rows($result);
If ($Count == 0 )
{
$sql = "INSERT INTO $landCon (West,North,Type1) VALUES ($West,$North,'$Char')";
mysql_query($sql) or die("Error occurred in RootA as:[$sql]: " . mysql_error());
}
else
{
$result=mysql_query("UPDATE $landCon SET Type1= '$Char' WHERE North = $North AND West=$West") or die( "Database Error: ".mysql_error());
}
echo "SUCCESS";
}
Instead of it updating where an entry exists it is inserting. My intention is to have it update if there is already the specified $North and $South entry so that there is only one North/South value per map grid.
$count = mysql_num_rows($result);
If ($Count == 0 )
Is $count $Count ?
captcha: languages that silently initialize new variables when you make a typo

Run code on publish/update of Wordpress page

I've built a website using Wordpress.
I have a template that has the following code, it is geocoding an address and saving the result into a new database.
I then have another template that reads all the lat/lng's from the new database and plots hundreds of markers on a Google map.
The problem is that the geocoding only happens when someone visits the page. This creates a couple of problems - 1) It geocodes EVERY time someone visits the page. 2) It ONLY geocodes when someone visits the page!
Is there a way to run this code ONCE when Wordpress publishes/updates the page?
This section grabs the company info from Wordpress and inserts it into the database:
$company = get_field('company_name');
$address = get_field('address');
$city = get_field('city');
$post_code = get_field('post_code');
$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`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '')");
}
wp_reset_query();
Here's the full code:
<?php
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("medicom_wp", $con);
$company = get_field('company_name');
$address = get_field('address');
$city = get_field('city');
$post_code = get_field('post_code');
$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`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '')");
}
wp_reset_query();
define("MAPS_HOST", "maps.google.com");
define("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());
}
// Select all the rows in the markers table
$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/geo?output=xml" . "&key=" . KEY;
// Iterate through the rows, geocoding each address
while ($row = #mysql_fetch_assoc($result)) {
$geocode_pending = true;
while ($geocode_pending) {
$address = $row["address"];
$id = $row["id"];
$request_url = $base_url . "&q=" . urlencode($address);
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0) {
// Successful geocode
$geocode_pending = false;
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = split(",", $coordinates);
// Format: Longitude, Latitude, Altitude
$lat = $coordinatesSplit[1];
$lng = $coordinatesSplit[0];
$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);
if (!$update_result) {
die("Invalid query: " . mysql_error());
}
} else if (strcmp($status, "620") == 0) {
// sent geocodes too fast
$delay += 1000;
} else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocoded. ";
echo "Received status " . $status . "
\n";
}
usleep($delay);
}
}
?>
In general:
In a plugin (or in the file functions.php located in your theme) you have the following code:
add_action('publish_post', function($post_id) {
// Here you have some code that finds out the geocode data
// then you attach it to this post as a meta value
update_post_meta($post_id, 'my_geocode', $geo_data);
});
Then in your template file (single.php) you will have somehting like:
$geo_data = get_post_meta($post->ID, 'my_geocode', true);
if( $geo_data ) {
get_template_part('geocode');
}
Or if you want to keep your template files clean you can add action "the_content"
in the file functions.php located in the theme directory (or in your plugin file)
add_action('the_content', function() {
if( is_singular() ) {
global $post;
$geo_data = get_post_meta($post->ID, 'my_geocode', true);
if( $geo_data ) {
get_template_part('geocode');
}
}
});
Do a google search like "wordpress add_action". Wordpress lets you "listen" to different events taking place within wordpress. In your case I think you can use the action named "update_post".

How to execute script without visiting page

I have a wordpress site that contains hundreds of company profiles. Each company has an address that is geocoded when someone visits their profile. At present that's the only way the address get's geocoded, so if no one visits the page then the address doesn't get geocoded.
That also creates another problem, it geocodes the address every time someone visits the page!
I need to come up with a way that will trigger the geocoding once for each company BUT without having to visit the page.
Is there any way this can be done?
UPDATE:
This is the script that is triggered when you visit a company profile (i.e the geocoding). So for 300 companies you would need to visit all 300 pages for all of them to be geocoded!
<?php
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("medicom_wp", $con);
$company = get_field('company_name');
$address = get_field('address');
$city = get_field('city');
$post_code = get_field('post_code');
$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`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '')");
}
wp_reset_query();
define("MAPS_HOST", "maps.google.com");
define("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());
}
// Select all the rows in the markers table
$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/geo?output=xml" . "&key=" . KEY;
// Iterate through the rows, geocoding each address
while ($row = #mysql_fetch_assoc($result)) {
$geocode_pending = true;
while ($geocode_pending) {
$address = $row["address"];
$id = $row["id"];
$request_url = $base_url . "&q=" . urlencode($address);
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->Response->Status->code;
if (strcmp($status, "200") == 0) {
// Successful geocode
$geocode_pending = false;
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = split(",", $coordinates);
// Format: Longitude, Latitude, Altitude
$lat = $coordinatesSplit[1];
$lng = $coordinatesSplit[0];
$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);
if (!$update_result) {
die("Invalid query: " . mysql_error());
}
} else if (strcmp($status, "620") == 0) {
// sent geocodes too fast
$delay += 1000;
} else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocoded. ";
echo "Received status " . $status . "
\n";
}
usleep($delay);
}
}
?>
Assuming you are doing the geocoding on the server, then to solve the problem of looking up the data each time, just cache the result.
Your logic will then look something like:
if geocode in database
get data from database
else
get data from geocode lookup
store data in database
return data
If you really want to avoid doing it on demand (i.e. not even the first time), then do what I have in "else" there when you save a page.

Categories