Update a DB using data retrived from a while loop - php

I Have a table named FRANCE like this
City Region LAT LNG
PARIS L'Ile-de-France
MARSEILLE Provenza
Now, LAT and LNG values I retrieve throught a function that use google api. To do this I must concatenate City and Region
So this is what I do:
$sql="Select * from France";
$result=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($result)){
$city=$row['city'];
$region=$row['region'];
$address=$city.",".$region.", France";
$coordinates = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=true');
$coordinates = json_decode($coordinates);
$lat = $coordinates->results[0]->geometry->location->lat;
$lng = $coordinates->results[0]->geometry->location->lng;
}
Now I'd like to update the table FRANCE to have this output
City Region LAT LNG
PARIS L'Ile-de-France 48.856614 2.352222
MARSEILLE Provenza 43.296482 5.369780
How can I do?

It's quite straightforward, just like the comments above, you already got the fetching of results and made the request. After gathering the response from the request just make that UPDATE statement.
Obligatory note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here is a rough untested example using mysqli with prepared statements. Of course you need to modify those items:
// first step connect and make the first query
$db = new mysqli('localhost', 'username', 'password', 'database');
$sql = 'SELECT * FROM france';
$query = $db->query($sql);
while($row = $query->fetch_assoc()) {
// fetch and assign results
$id = $row['id'];
$city = $row['city'];
$region = $row['region'];
$address = $city.",".$region.", France";
// make the google request and gather results
$coordinates = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=true');
$coordinates = json_decode($coordinates);
// check if there are results
if($coordinates != null) {
$lat = $coordinates->results[0]->geometry->location->lat;
$lng = $coordinates->results[0]->geometry->location->lng;
// make the update
$sql2 = 'UPDATE france SET `LAT` = ?, `LNG` = ? WHERE id = ?';
$update = $db->prepare($sql2);
// i don't know if this is double column or varchar
$update->bind_param('ddi', $lat, $lng, $id);
$update->execute();
}
}

Related

PHP MySQL WHERE column-value is in $_POST

I'm trying to get all the rows which contain a particular text. However, when I execute the query, no rows are returned. I'm retrieving the text from a post request which looks like this "Krachttraining,Spinning" (= 2 values). I think my code fails on the following part (if I leave this out, the query returns some rows): AND CONCAT('%', sport.name, '%') LIKE $sports.
FYI. I know you can perform SQL injection on this, this will be fixed later.
<?php
$servername = "SECRET";
$username = "SECRET";
$dbpassword = "SECRET";
$dbname = "SECRET";
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$sports = $_POST['sports'];
echo $sports; //Echo's: Krachttraining,Spinning.
// Create connection.
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
// Check connection.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT gym.id FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND CONCAT('%', sport.name, '%') LIKE $sports";
$result = $conn->query($sql);
$output = array();
if ($result->num_rows > 0) {
// output data of each row.
while($row = $result->fetch_assoc()) {
$id = $row["id"];
array_push($output, $gym);
}
//Brackets because of GSON's parser.
echo "[" . json_encode($output) . "]";
}
$conn->close();
?>
EDIT: Changed SQL statement to:
$sql = "SELECT * FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND sport.name LIKE '%".$sports."%'";
Still getting 0 rows returned.
EDIT 2: I ran the following code in my phpMyAdmin environment, and it returned 0 rows.
Select * FROM sport WHERE name LIKE '%Krachttraining,Spinning%';
However when I'm running the following code, it returns 1 row:
Select * FROM sport WHERE name LIKE '%Krachttraining%';
I don't really get it what I'm doing wrong, any thoughts?
I think you want to use the IN statement.
This will check if any word in the array matches. For instance:
Select * FROM sport WHERE name IN ('Spinning', 'Krachttraining'); Will return every row which has the name Spinning or Krachttraining.
Just use:
SELECT .FROM...WHERE AND sport.name LIKE '%".$sports."%'";
After question editing
After you changed the question, I suggest to take a look at this answer to better understand what you should to do: https://stackoverflow.com/a/3902567/1076753
Anyway I think that you have to learn a bit about the like command: http://www.mysqltutorial.org/mysql-like/
Change the sql to :
$sql = "SELECT gym.id FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND sport.name LIKE '%".$sports%."'";

Reading spatial data from MySQL using PHP

I have a website that manages points of interest, using PHP and MySQL. I decided to look at MySQL's Spatial Data features instead of saving the coordinates in two separate fields.
I managed to get the inserting of data into the database using the following:
// Update new records
$query = "UPDATE users SET users_address = :uaddress, users_placeid = :uplace, users_coords = POINTFROMTEXT(:location) ";
$query .= "WHERE users_id = :uid ";
// echo "Query: $query <br>";
$stmt = $conn->prepare($query);
$stmt->execute(array(':uaddress' => $users_address,
':uplace' => $users_placeid,
':location' => $location,
':uid' => $users_id));
$result = $stmt;
Now I want to read the data and get the coordinates out, using PHP and PDO. There does not seem to be any examples on the Internet for using PDO, PHP and MySQL for spatial data.
My normal SELECT code is:
$stmt = $conn->prepare("SELECT * FROM users WHERE users_id = :uid ");
$stmt->execute(array(':uid' => $users_id));
$result = $stmt;
if ($result->rowCount() > 0) {
foreach($result as $row) {
$users_address = $row['users_address'];
$users_placeid = $row['users_placeid'];
$users_lat = $row['x.users_coords'];
echo "Lat: $users_lat <br>";
}
}
I've tried various options and each one gives an error. The code above returns:
Notice: Undefined index: x.users_coords
I want to stick to using SELECT * instead of SELECT users_address, etc. if possible.
The other option is to just return to using two fields for the coordinates, but that makes it more difficult to do distance measurements etc later.
Any idea how to extract Latitude and Longitudes?
After much frustration I managed to solve the problem. You have to specify the spatial data in the SELECT string and then it is easy to read the data. Here is full code to read the data:
$stmt = $conn->prepare("SELECT *, X(users_coords) AS users_lat, Y(users_coords) AS users_long FROM users WHERE users_id = :uid ");
$stmt->execute(array(':uid' => $users_id));
$result = $stmt;
if ($result->rowCount() > 0) {
foreach($result as $row) {
$users_address = $row['users_address'];
$users_placeid = $row['users_placeid'];
$users_lat = $row['users_lat'];
// echo "Lat: $users_lat <br>";
$users_long = $row['users_long'];
// echo "Long: $users_long <br>";
}
}
?>

assigning variables to sql query result

Amateur here, just practicing some sql.
I am trying to assign php variables to my sql query results, and I thought I saw it work in this fashion, but it doesn't seem to be working for me:
$query1 = mysql_query("SELECT * FROM markers WHERE id = '$markerid'");
$result = mysql_query($query1);
$markerData = mysql_fetch_array($result, MYSQL_ASSOC);
$name = $markerData['name'];
$description = $markerData['description'];
$directions = $markerData['directions'];
$lat = $markerData['lat'];
$lng = $markerData['lng'];
$type = $markerData['type'];
$addedby = $markerData['addedby'];
Is there some rule I am blatantly disregarding?
Additionally, I know sql is deprecated/unsafe, just trying to learn the basics here.
Sincere thanks for any help.
You should feed a query statement into the mysql_query function, not feed it with another mysql query:
$sql = "SELECT * FROM markers WHERE id = '$markerid'";
$result = mysql_query($sql);
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
It doesn't matter if you're still in the starting stage. Since you already know that API is deprecated and your queries are usafe, why not just start good habits.
This is by way of PDO with prepared statements:
$db = new PDO('mysql:host=localhost;dbname=DB_NAME', 'username', 'password');
$sql = 'SELECT * FROM markers WHERE id = :markerid';
$select = $db->prepare($sql);
$select->bindParam(':markerid', $markerid, PDO::PARAM_INT);
$select->execute();
$markerData = $select->fetch(PDO::FETCH_ASSOC);
$name = $markerData['name'];
$description = $markerData['description'];
$directions = $markerData['directions'];
$lat = $markerData['lat'];
$lng = $markerData['lng'];
$type = $markerData['type'];
$addedby = $markerData['addedby'];
You can loop trough your results like this:
while ($row = mysql_fetch_assoc($result)) {
echo $row["name"];
echo $row["description"];
echo $row["directions"];
echo $row["lat"];
echo $row["lng"];
echo $row["type"];
echo $row["addedby"];
}
And your query should take a sql statement like this:
$sql = "SELECT * FROM markers WHERE id = '$markerid'";
$result = mysql_query($sql);
You can use query like this.
SELECT * FROM "markers" "t" WHERE "id" = ''.$markerid.'';

second mysqli_query fails

the first query is fine but the second one wont work it just dies.
I plug the $city variable into the second one and echo it back and it shows the correct
value but its the the actual:
$row = mysqli_query($dbc, $query)
or die('Error while querying the Database');
that fails... please help!
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or WriteMessage('Error', 'Could not connect to the Database...');
//get user city...
$userID = $_SESSION['userID'];
$queryUserCity = "SELECT * from user where userID = $userID";
$GetResult = mysqli_query($dbc, $queryUserCity)
or die('Error while querying the Database');
$getRow = mysqli_fetch_array($GetResult);
$city = $getRow['city'];
$state = $getRow['state'];
$username = $getRow['username'];
echo 'username='.$username.' ';
echo 'city='.$city;
echo 'state = ' .$state;
$query = "SELECT * FROM adds where city = $city ORDER BY addDate ASC";
//fails right here...
/*-->*/ $row = mysqli_query($dbc, $query)
or die('Error while querying the Database');
echo $query;
exit();
while($row = mysqli_fetch_array($data))
{
You are trying to find a string without single quote. You use integer without single quote but in case of string you have to use single quote with your string.
change
$query = "SELECT * FROM adds where city = $city ORDER BY addDate ASC";
to
$query = "SELECT * FROM adds where city = '$city' ORDER BY addDate ASC";
and to find out exact error try to use the below code.
if (!mysqli_query($dbc, $query)){
echo("Error description: " . mysqli_error($dbc));
}
If the city is a textual type (and it probably is), you'll need:
... where city = '$city' ...
But, in fact, you shouldn't really be doing it that way anyway, since it opens you up to the possibility of SQL injection attacks if someone can enter arbitrary text for their city.
You should start looking into parameterised queries since they can protect you from such attacks. See Exploits of a Mom and the invaluable explain-xkcd entry.

Can not update records from one table into another

Hi I have a postcode database which contains postcodes and the lat and lon details, In another table i have a list of companies with postcodes and want to add the lat and lon details to matching postcodes, rather than use a join query etc. Below is the code i am using, i have used something similar before, but i just can not work out why this isn't working.
$host = "localhost";
$username = "";
$password = "";
$database = "";
mysql_connect( $host, $username, $password );
mysql_select_db( $database ) or die( "Unable to select database" );
$query = "SELECT * FROM postcodes";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$postcode = $row['postcode'];
$lat = $row['lat'];
$lon = $row['lon'];
$result = mysql_query("UPDATE companies SET lat ='$lat' and lng ='$lon'
WHERE postal_code = '$postcode'")
or die(mysql_error());
}
The error I am getting is: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/visitrac/public_html/postcode.php on line 15
if i move the closed bracket so it is before the update then the error goes but no information gets into the database, which i assume is because it is out of the loop. I have tried all sorts of things but nothing seems to work and so any nudges in the right direction would be appreciated.
Thanks
There's really no need for the loop through the postcode results. You can update all companies in a single SQL statement.
UPDATE companies c
INNER JOIN postcodes p
ON c.postal_code = p.postcode
SET c.lat = p.lat,
c.lng = p.lon
try this:
"UPDATE companies SET lat ='"+$lat+"' and lng ='"+$lon+"'
WHERE postal_code = '"+$postcode+"'"

Categories