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+"'"
Related
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%."'";
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();
}
}
I want to count the rows in the users table with specific name and pwd which should be 1 if existed.
but the result always return null(not 0),no matter whether the user existed or not.
I even change the query simple to "SELECT * FROM users", and it ended with the same result.
And I am pretty sure that the name of the DATABASE and TABLE are true,and the table is not empty!
By the way,why I have to use "#" symbol before "mysqli_query" in order to get rid of error?
thx!
enter code here
<?php
#$mysql_db_hostname = "localhost";
$mysql_db_hostname = "127.0.0.1";
$mysql_db_user = "root";
$mysql_db_password = "";
$mysql_db_database = "smartFSUsers";
$con = mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,$mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$name = $_GET["name"];
$password = $_GET["password"];
$query = "SELECT * FROM users WHERE name='$name' AND password='$password'";
$result =#mysqli_query($query,$con);
echo($result);
$row=#mysqli_num_rows($result);
echo"the row num is $row \n";
?>
RTM: http://php.net/mysqli_query
$result =#mysqli_query($query,$con);
You've got your parameters reversed. $con MUST come first:
$result = mysqli_query($con, $query) or die(mysqli_error());
If you had bothered adding error correction to your code, you'd have been told about this. But nope, you opted for # to hide all those error messages.
I am currently trying to get a data(M_Name) from a table called Merchant.
Following are my codes:
<?php
$response = array();
$link = mysql_connect('localhost','root','') or die ('Could not connect: '.mysql_error());
mysql_select_db('ichop') or die ('Could not connect to database');
$result = mysql_query("select * from offer") or die(mysql_error());
if(mysql_num_rows($result) > 0){
$response["offers"] = array();
while($row = mysql_fetch_array($result)){
$offer = array();
$offer["offer_id"] = $row["Offer_ID"];
$offer["start_date"] = $row["Start_Date"];
$offer["end_date"] = $row["End_Date"];
$offer["o_desc"] = $row["O_Desc"];
$offer["short_desc"] = $row["Short_Desc"];
$offer["merchant_ID"] = $row["Merchant_ID"];
$offer["m_name"] = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'");
array_push($response["offers"], $offer);
}
$response["success"] = 1;
echo json_encode($response);
} else {
//no offer found
$response["success"] = 0;
$response["message"] = "No offer found";
echo json_encode($response);
}
?>
When I run this PHP file using web browser, I couldn't get the desired name for the merchant even though the data is there in the database...it would just return me "null".
{"offers":[{"offer_id":"1","start_date":"2013-05-17","end_date":"2013-05-18","o_desc":"AAA","merchant_ID":"2","m_name":null}],"success":1}
What have I done wrong or what am I still missing? Please help..thanks!
I would rather use LEFT JOIN mysql function and get all relevant data at first query from both of your tables
SELECT * FROM offer a LEFT JOIN MERCHANT b ON a.Merchant_ID = b.MERCHANT_ID
so you won't have to make any extra query and you can store your value directly in your array
$offer["m_name"] = $row['M_Name'];
Then I would like you to remember that mysql_* functions are deprecated so i would advise you to switch to mysqli or PDO
The mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'"); does not return a value from the DB, you need to follow it up with for example mysql_fetch_array like you did with the other query to the DB.
There is a solution more simple: use a JOIN, which combines two tables.
SELECT offer.*, MERCHANT.M_Name
FROM offer
LEFT JOIN MERCHANT ON(MERCHANT.MERCHANT_ID = offer.merchant_ID)
look like you have to return an result from query instead of while,
mysql_fetch_array(mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'"));
but had better you make some error hadling first
You can use below one
$resMerchant = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'");
$rowMerchant = mysql_fetch_assoc($resMerchant);
$offer["m_name"] = $rowMerchant['M_Name'];
$offer["m_name"] = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'")
mysql_query() does not return a string but a resource. You'll have to fetch the result.
Also, don't forget that mysql_* is now deprecated.
[edit]
As stated by Fabio, you'd rather use JOIN on your query. At the moment, you are making a request in your loop. That's useless (INNER JOIN or LEFT JOIN are what you want) and very resource consumming.
I am trying to get hold of 1 record from a MySQL table using PHP. I have tried many different SELECT statements, while they all work in MYSQL they refuse to return any result in php.
The countriesRanking table is a simple two column table
country clicks
------ ------
0 222
66 34
175 1000
45 650
The mysql returns the ranking of the country column (1, 2, 3, etc..) and it returned all results EXCEPT the first ranked country. Eg when country=175, should return 1 but no result returned. Direct query via web browser return blank page, no error message. My PHP code
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country'") or die(mysql_error());
$row = mysql_fetch_assoc($result) or die(mysql_error());
$theranking = $row['rank'];
echo $theranking;
EDIT
I tried the following but get the same blank page
var_dump($row['rank']);
EDIT 2
For a successful query print_r($result) returned something like Resource id #4. While print_r($row) returned Array ( [0] => 4 [rank] => 4 ). But when querying for the top ranking country. eg country=175, it returned a blank page.
Give this a try. It is based on your earlier question. MYSQL returns empty result in PHP
MYSQLI version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysqli_connect($hostname,$user,$password,$database);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 175";
$result = mysqli_query($link,$query);
$arr_result = mysqli_fetch_array($result,MYSQLI_BOTH);
return $arr_result['rank'];
}
mysqli_close($link);
}
echo rank();
?>
MYSQL version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysql_connect($hostname,$user,$password);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 66";
mysql_select_db($database);
$result = mysql_query($query);
$arr_result = mysql_fetch_array($result,MYSQL_BOTH);
return $arr_result['rank'];
}
mysql_close($link);
}
echo rank();
?>
Assuming you are not getting an error that means you are successfully connecting to your database. You are just not getting back any values.
Try:
$row = mysql_fetch_row($result);
I would usually think $row = mysql_fetch_assoc($result); would work but if neither of these work it must be something within your mysql_query.
You can debug this as below.
make sure your SQL is correct by running it on PHPMyAdmin and check the result.
make sure you don't have any fatal errors, if you get a blank page there is something wrong. Turn on PHP errors and see.
print_r($result) and see whether it's empty.
if you want first ranking only then add the LIMIT 1 to your query
If you want only one record from database than you have to use limit in query
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country' LIMIT 1") or die(mysql_error());
and after that use while loop
while($row = mysql_fetch_assoc($result)) {
$theranking = $row['rank'];
}
echo $theranking;