Storing time (periods) (Specific hours) (Durations) using HTML/PHP - Days/Hours - php

I have been working on a page that stores opening hours of days of the week using html and php to the database. In order to use the data entries to compare it with the current time.. I did my best but its not working. I'm gonna show you the html, php, sql codes so you can tell me how can I solve it.
HTML+CSS Code of the form:
http://jsfiddle.net/Naz970/4y4sd91u/
SQL :
CREATE TABLE IF NOT EXISTS `markers` (
`id` int(11) NOT NULL,
`name` varchar(60) NOT NULL,
`phone` int(100) NOT NULL,
`address` varchar(80) NOT NULL,
`email` varchar(100) NOT NULL,
`link` varchar(200) NOT NULL,
`lat` float(10,6) NOT NULL,
`lng` float(10,6) NOT NULL,
`type` varchar(30) NOT NULL,
`days` varchar(100) CHARACTER SET utf8 NOT NULL,
`openingHours` varchar(255) NOT NULL,
`img` blob NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=51
PHP Code:
<?php
include ("../Connections/Connection.php");
if (isset($_POST["submit"])) {
$name = $_POST["name"];
$type = $_POST["type"];
$address = $_POST["address"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$link = $_POST["link"];
$lng = $_POST["lng"];
$lat = $_POST["lat"];
$days = implode(";", $_POST['days']);
$openingHours = implode(";", $_POST['openingHours']);
$img = time().$_FILES['photo']['name'];
if (!move_uploaded_file($_FILES['photo']['tmp_name'],'../Uploads/'.$img)) die("error");
$sql = "INSERT INTO markers (name, type, address, email, phone, link, lng, lat, days, openingHours, img)
VALUES('$name', '$type', '$address', '$email', '$phone', '$link', '$lng', '$lat', '$days', '$openingHours', '$img')";
$query = mysql_query($sql);
if (!$query) {
die("Error : " . mysql_error());
}
if (empty($name) || empty($type) || empty($address) || empty($email) || empty($phone) || empty($lng) || empty($lat) || empty($days) || empty($openingHours) || empty($img)) {
echo "You did not fill out the required fields.";
die(); // Note this
}
echo "<center></center>";
}
?>
But the form (the time table (schedule)) is not working and not storing the data properly. I am using it to do the following:
PHP code of the marker comparison
<?php
require("config.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",'&apos;',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// 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());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$days = explode(";", $row['days']);
$openingHours = explode(";", $row['openingHours']);
$currentTime = date('H');
if (in_array($currentTime, $openingHours)) {
$status = 'Open';
}
else {
$status = 'Closed';
}
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo 'status="' . $status . '" ';
echo 'currentTime="' . $currentTime . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
I know the code is long but this is the only way to show you so you can tell me how can fix the issue of time of opening hour and link it with the marker and the current time.
If you have any question dont hesitate to ask me
Thanks in advance

Related

MySQL Database not Updating when Form Submitted using PHP

This is a webpage that I have:
// Info to connect to the Wishlist database
$servername = "em";
$dbusername = "";
$password = "!19";
$dbname = "";
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
// If unable to connect to the database display this error
if ($conn->connect_error) {
echo "Connection to wishlist failed";
die("Connection failed: " . $conn->connect_error);
}
echo "Once you have added creatures to your wishlist, click " .
"<strong><a href='http://eggcavity.com/edit-wishlist'>here</a></strong> to edit your wishlist.";
// Get current user's username
$current_user = wp_get_current_user();
$username = $current_user->user_login;
// Retrieve data from the database
$sql = "SELECT Name, Stage1 FROM Creatures";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_assoc()) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creautres[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><input type="submit" value="Submit"></form>';
} else {
echo "Creatures not found";
}
if(isset($_POST['submit'])){
foreach($_POST['creatures'] as $selected){
$sql = "INSERT INTO " . $username .
" (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" .
$selected . "', 'http://static.eggcave.com/90x90/" . $selected .
"_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($sql) === FALSE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
// Close the connection to the database
$conn->close();
It displays like I want it to:
But it doesn't update the database when I click the submit button.
I've tried echoing $stmt, it seemed to be written as it should be.
When I try echoing $selected, within the loop it doesn't seem to output anything.
Can you help me?
I have updated the code to use one database. Please help me. It still isn't adding.
You had a typo in your checkbox name. I re-did the submit line in the form and the isset() I believe.
The below includes activating error reporting, a try/catch, binding for safety against sql injection. The data saves. You will need to deal with what should be unique data getting saved more than once of course. For instance, a unique key on (Creature,Username). And I would re-think the columns for Id's, but this was your table design. Thanks for allowing us to show you a re-use of a table. Good luck.
schema (from you):
drop table if exists Wishlists;
CREATE TABLE `Wishlists` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Creature` varchar(100) DEFAULT NULL,
`Picture` varchar(200) DEFAULT NULL,
`Stage` varchar(100) DEFAULT NULL,
`Gender` varchar(100) DEFAULT NULL,
`Frozen` varchar(100) DEFAULT NULL,
`Notes` varchar(500) DEFAULT NULL,
`Username` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB; -- <------------------------ went with InnoDB
-- truncate table Wishlists; -- used during early testing
PHP (eggs01.php):
// Info to connect to the Wishlist database
$servername = "serve it up";
$dbusername = "dbu dbu dbu";
$password = "OpenSesame";
$dbname = "my db name";
try {
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
echo "I am connected and feel happy.<br/>";
if(isset($_POST['submit'])){
// Postback - submit
// Get current user's username
//$current_user = wp_get_current_user(); // remmed out, I don't have your system
//$username = $current_user->user_login; // remmed out, I don't have your system
$theCount=0;
foreach($_POST['creatures'] as $selected){
$Creature=$selected;
$Picture="http://static.eggcave.com/90x90/" . $selected . "_1";
$Stage="Stage1";
$Gender="Unspecified";
$Frozen="Unspecified";
$Notes="Unspecified";
$Username="Stackoverflow123";
$sql = "INSERT Wishlists (Creature, Picture, Stage, Gender, Frozen, Notes, Username) " .
" VALUES (?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql); // SQL Injection - safe prepare / bind / execute
// 7 s's means 7 strings:
$stmt->bind_param('sssssss', $Creature, $Picture, $Stage, $Gender, $Frozen, $Notes, $Username);
$stmt->execute();
$theCount++;
}
echo "<br>Santa has been notified, count = ".$theCount."<br>";
}
else {
// Just display the form
// Retrieve data from the database
$result = $conn->query("SELECT Name, Stage1 FROM Creatures");
if ($result->num_rows > 0) {
// Display all of the data from the database
echo '<form method="POST">';
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo '<div style="display: inline-block; width: 30%;">' .
'<img src="' . $row["Stage1"] . '"><br>'.
$row["Name"] .
'<br><input type="checkbox" name="creatures[]" value="' .
$row["Name"] .
'"></div>';
}
echo '<br><br><button type="submit" name="submit">Submit</button></form>';
$result->close();
} else {
echo "Creatures not found";
}
}
} catch (mysqli_sql_exception $e) {
throw $e;
}
After the submit having selected 3 eggs:
Database Image:
First of all, look at code
$dbname1 = *****";
Here you are missing " :
So replace this with
$dbname1 = "*****";
and try again
First issue is you should never run a SQL statement in a Loop ALWAYS AVOID THIS - as it will put your server through a lot of strain.
And 2nd try this and tell me the out put
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
if ($conn->query($stmt) === TRUE) {
}
}
TO
foreach($_POST['creatures'] as $selected){
$stmt = "INSERT INTO " . $username . " (Creature, Picture, Stage, Gender, Frozen, Notes) VALUES ('" . $selected . "', 'http://static.eggcave.com/90x90/" . $selected . "_1', 'Stage1', 'Unspecified', 'Unspecified', 'Unspecified', '')";
$result = $conn->query($stmt) OR die(var_dump($conn));
var_dump($result->fetch_array(MYSQLI_ASSOC));
die;
}

Get Radio Group Value

I am developing a page for multiple choice questions. User is only able to select an answer for each question. I can't seem to retrieve the value (1 indicates correct answer) of the radio buttons.
Here is structure of two tables that I use
CREATE TABLE IF NOT EXISTS `question` (
`q_id` int(10) NOT NULL AUTO_INCREMENT,
`q_qstn_no` int(11) NOT NULL,
`q_text` varchar(300) NOT NULL,
`q_chpt` int(11) NOT NULL,
PRIMARY KEY (`q_id`)
)
CREATE TABLE IF NOT EXISTS `answer` (
`a_id` int(6) NOT NULL AUTO_INCREMENT,
`q_id` int(10) NOT NULL,
`a_text` varchar(255) NOT NULL,
`a_value` tinyint(1) NOT NULL,
PRIMARY KEY (`a_id`)
)
HTML form containing the radio group.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL ^ E_NOTICE);
session_start();
if(isset($_SESSION['tf1_sid']))
{
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="ques_page_calc1.php">
<p>Questions</p>
<table width="900" border="0" cellpadding="4">
<?php
// db connect
include("dbconn.php");
// db query for questions
$sql_q = "SELECT q_id, q_qstn_no, q_text FROM question";
$query_q = mysql_query($sql_q) or die("MySQL Error: " . mysql_error());
// start loop for questions
$rad2 = 0;
while($data_q = mysql_fetch_array($query_q, MYSQL_ASSOC)){
// echo "<pre>";
// print_r($data_q);
// echo "</pre>";
//
echo "<tr><td width='25' align='center' valign='top'><label><input name='q_no' size='1' type='hidden' value=". $data_q['q_qstn_no'] .">". $data_q['q_qstn_no'] ."</label></td>";
echo "<td>". $data_q['q_text'] ."<br />";
// db query for answers
$sql_a = "SELECT a_id, a_text, a_value FROM answer WHERE q_id=".$data_q['q_id'];
$query_a = mysql_query($sql_a) or die("MySQL Error: " . mysql_error());
//$rad = 0;
// start loop for answers
while($data_a = mysql_fetch_array($query_a, MYSQL_ASSOC)){
echo "<br /><table width='750' border='0'>";
echo "<tr><td><label><input name='answer_".$rad2."' type='radio' value=". $data_a['a_value'] .">". $data_a['a_text'] . "</label></td></tr>";
echo "</table>";
//$rad++;
}
echo "</tr>";
$rad2++;
}
echo "<tr><td><input name='Submit' type='submit' onClick='ques_page_calc1.php' value='Submit'></td></tr>";
mysql_free_result($query_q);
mysql_free_result($query_a);
include("dbconn.php");
?>
</table>
</form>
</body>
</html>
<?php
}
else
{
header("Location:s_login.php");
}
?>
The PHP file to get the value selected
<?php
ini_set('display_errors',1);
error_reporting(E_ALL ^ E_NOTICE);
// include db connection file
include("dbconn.php");
session_start();
if(isset($_POST['Submit']))
{
$id = $_SESSION['tf1_sid'];
echo $id;
$correct = 0;
$ev_id = 1;
//db query to obtain i_id
$sql_i = "SELECT i_id FROM ins_stud WHERE s_id = '$id'";
$query_i = mysql_query($sql_i) or die("MySQL Error: " . mysql_error());
$data_i = mysql_fetch_array($query_i, MYSQL_ASSOC);
print_r($data_i);
// capture values from HTML form
if(!empty($_POST['answer_'.$rad2]))
{
foreach(($_POST['answer_'.$rad2]) as $ans)
{
echo $ans;
var_dump($_POST);
if($ans == 1)
$correct = $correct + 1;
}
//echo $correct;
// insert answer to table
//$sql_eval = "INSERT INTO eval_set (ev_id, q_id, response, created) VALUES ('" . $ev_id . "', '" . $ques_no . "', '" . $ans . "', CURDATE())";
//mysql_query($sql_eval) or die ("Error: " . mysql_error());
//}
}
//
// insert result to table
//$sql_result = "INSERT INTO result (r_score, ev_id, s_id, i_id) VALUES ('" . $correct . "', '" . $ev_id . "', '" . $id . "', '" . $data_i . "')";
//mysql_query($sql_result) or die ("Error: " . mysql_error());
//echo "Result: " . $correct . " questions correct.";
//header("Location:ass_result.php");
}
// close db connection
mysql_close($dbconn);
?>
I thought it was the $_POST['answer_'.$rad2] that was causing the problem since I wasn't sure how to concatenate variables to name field. But now that's changed, there is still no output beyond print_r($data_i); line in the PHP file.
You don't need to give your radio group buttons different names. All of your choices will have a single name (say 'answer') and your PHP script will simply check for
$_POST['answer']
this will give you the selected radio button's value. So however many radio buttons you have for a certain question, give all of them the same name and you're fine. This will also make sure that only one of the radio buttons related to each other can be checked.
I solved it :) I took away the if(!empty...) and replaced it with these.
for($i=1;$i<=$qno;$i++){
$repStr = str_replace("1", $i, "answer_1");
//echo "Question ". $i .": ". $repStr;
$ans = $_POST[$repStr];
//echo "". $radio ."<br>";
if($ans == 1)
$correct = $correct + 1;
// everything before is FIXED :D
// insert answer to table
$sql_eval = "INSERT INTO eval_set (ev_id, q_id, response, created) VALUES ('MAX(ev_id)+1 ', '" . $i . "', '" . $ans . "', CURDATE())";
mysql_query($sql_eval) or die ("Error: " . mysql_error());
}

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".

xml to php and parse encoding error

I am parsing xml file from url(in code below), using file_get_contents() function, and simpleXML, to insert data into the table, i did well, but i have problem with encoding(russian words) i get this ->Черногория; file and database encoding is set to utf-8;
require_once 'mysql_connect.php';
/**
*
*
*/
error_reporting(E_ALL);
$sql = "CREATE TABLE IF NOT EXISTS `db_countries` (
`id` int(11) unsigned NOT NULL auto_increment,
`countrykey` varchar(255) NOT NULL default '',
`countryname` varchar(255) NOT NULL default '',
`countrynamelat` varchar(500) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
mysql_query($sql);
$data = file_get_contents("http://www2.turtess-online.com.ua/export/dictionary/countries/");
$xml = new SimpleXMLElement($data);
echo $xml->body->dictionary->element["countryName"];
foreach ($xml->body->dictionary->element as $element) {
$countryname = mysql_real_escape_string($element["countryName"]);
$countrynamelat = mysql_real_escape_string($element["countryNameLat"]);
$countrykey = $element["countryKey"];
if ($countrykey) {
$q = $insert = 'INSERT INTO db_countries (countrykey, countryname, countrynamelat) VALUES ("' . $countrykey . '", "' . $countryname . '", "' . $countrynamelat . '")';
mysql_query($q);
} else {
echo "not valid key of country";
}
}
Make sure you insert Unicode content as well, database charset is not doing any "automagic" conversion.
As an alternative, I would suggest utf8_encode($countryname) as in :
if ($countrykey) {
$q = $insert = 'INSERT INTO db_countries (countrykey, countryname, countrynamelat) VALUES ("' . $countrykey . '", "' . cp1251_to_utf8($countryname) . '", "' . $countrynamelat . '")';
mysql_query($q);
} else {
echo "not valid key of country";
}
update : indeed, the XML source file shows a Windows 1251 charset
UPDATE(2) : i tested the code against this nifty little function and it works at last :)
function cp1251_to_utf8($s)
{
if ((mb_detect_encoding($s,'UTF-8,CP1251')) == "WINDOWS-1251")
{
$c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
for($i=0; $i<strlen($s); $i++)
{
$c=ord($s[$i]);
if ($c>=192 and $c<=239) $t.=$c208.chr($c-48);
elseif ($c>239) $t.=$c209.chr($c-112);
elseif ($c==184) $t.=$c209.$c209;
elseif ($c==168) $t.=$c208.$c129;
else $t.=$s[$i];
}
return $t;
}
else
{
return $s;
}
}
credit goes to Martin Petrov

Adapt code to my mySQL tables

I have a table, "jos_ezrealty" that has address, city, state fields and declat & declong for latitude and longitude. I need to adapt the code below (provided by google - http://code.google.com/apis/maps/articles/phpsqlgeocode.html) to work with my table. All of my address fields are filled, and half of my lat & long fields are filled. I want to use the code below to fill in the missing lat & long information (don't worry about geocoding request limits, as I only have 300 properties and this code only fills in the missing ones)
Thanks -
<?php
require("phpsqlgeocode_dbinfo.php");
define("MAPS_HOST", "maps.google.com");
define("KEY", "abcdefg");
// 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 += 100000;
} else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocoded. ";
echo "Received status " . $status . "
\n";
}
usleep($delay);
}
}
?>
If I understood correctly you need to adapt your database schema into the code example provided by google.
If that is the case then if your database follows the google example i.e.
CREATE TABLE `markers` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 60 ) NOT NULL ,
`address` VARCHAR( 80 ) NOT NULL ,
`lat` FLOAT( 10, 6 ) NOT NULL ,
`lng` FLOAT( 10, 6 ) NOT NULL ,
`type` VARCHAR( 30 ) NOT NULL
) ENGINE = MYISAM ;
You only have to rename your table to markers or change and change the $database value at the phpsqlgeocode_dbinfo.php or change the queries to select your table.
Otherwise please specify your problem.

Categories