I am trying to update one database based on the data of another.
Basically the road no, the block no, and the building no are in both databases, but the one contains the lats and longs and the other doesn't. So I am trying to update the lats and longs to the other.
Here is what I did.
<?php
mysql_connect("localhost", "root", "test") or die(mysql_error());
mysql_select_db("class") or die(mysql_error());
$data = mysql_query("SELECT * FROM testdata WHERE lat2='' And lon2 = ''"); // Selects from the database without lats and longs
$address = mysql_query("SELECT * FROM address ") // selects from database with lats and longs
or die(mysql_error());
while($infodata = mysql_fetch_array( $data ))
{
$infoaddress = (mysql_fetch_array($address));
$BuildingA = $infoaddress['Building']; // A stands for Address where is the database address
$RoadNoA = $infoaddress['RoadNo'];
$BlockA = $infoaddress['Block'];
$BuildingD = $infodata['Building']; // D stands for testData which is the same database
$RoadNoD = $infodata['RoadNo'];
$BlockD = $infodata['Block'];
$idA = $infoaddress['id']; // ID for address
$idD = $infodata['id']; // ID for Data
$lat = $infoaddress['lat']; // get the lats and longs
$lon = $infoaddress['lon'];
if ($BuildingA = $BuildingD && $RoadNoA = $RoadNoD && $BlockA = $BlockD)
{ // do the logical test
mysql_query("UPDATE testdata SET lat2='$lat', lon2='$lon' WHERE id='$idD'"); // update the values
}
else
mysql_query("UPDATE testdata SET lat2='', lon2='' WHERE id='$idD'"); // update the values
}
?>
What happens is that it does update the testdatabase, but for some reason, it has the wrong lats and longs, even when I type in a wrong road and block and building no that don't exist in the address database, it updates it with some lats and longs.
It is important that all 3 conditions be true.
Any suggestions?
Try this, Use == instead of =
if ($BuildingA == $BuildingD && $RoadNoA == $RoadNoD && $BlockA == $BlockD)
instead of
if ($BuildingA = $BuildingD && $RoadNoA = $RoadNoD && $BlockA = $BlockD)
I suspect what you're really looking for is an UPDATE with a JOIN:
UPDATE testdata t
JOIN address a USING (Building, RoadNo, Block)
SET t.lat2 = a.lat, t.lon2 = a.lon
WHERE t.lat2 = '' AND t.lon2 = ''
Related
I am trying to update multiple rows in a single query. Data doesnt get updated in my code. I am trying to join the two tables. When user enters a no. The data from the 2 tables will be displayed which is connected through the foreign key.The data from the table1 gets updated. Where as the columns from the table 2 doesnt get updated. I need to update the second table based on unique id
if($_REQUEST["profile"] == "profile")
{
$Id = $_REQUEST["id"];
$firstname = mysql_real_escape_string($_REQUEST["firstname"]);
$serial = mysql_real_escape_string($_REQUEST["serial"]);
$dom = mysql_real_escape_string($_REQUEST["dom"]);
$idno = $_REQUEST["idno"];
$pow = mysql_real_escape_string(stripslashes($_REQUEST["pow"]));
$address = mysql_real_escape_string(stripslashes($_REQUEST["address"]));
$bookno = mysql_real_escape_string(stripslashes($_REQUEST["bookno"]));
$zone = mysql_real_escape_string(stripslashes($_REQUEST["zone"]));
$mobile = mysql_real_escape_string(stripslashes($_REQUEST["phone"]));
$phone = mysql_real_escape_string(stripslashes($_REQUEST["mobile"]));
$mothertongue=mysql_real_escape_string(stripslashes($_REQUEST["mothertongue"]));
$nof=mysql_real_escape_string(stripslashes($_REQUEST["nof"]));
$email=mysql_real_escape_string(stripslashes($_REQUEST["email"]));
$nom=$_REQUEST["nom"];
$nofemale=$_REQUEST["nofemale"];
mysql_query("UPDATE profile SET firstname='".$firstname."',serial='".$serial."',dom='".$dom."',idno='".$idno."',pow='".$pow."',address='".$address."',bookno='".$bookno."',
zone='".$zone."',phone='".$mobile."',mobile='".$phone."',mothertongue='".$mothertongue."',email='".$email."',nof='".$nof."',nom='".$nom."',nofemale='".$nofemale."' WHERE id = '".$_POST['id']."' " ) or die(mysql_error());
for($i=0;$i<count($_REQUEST['slno1']);$i++)
{
$mid=$_REQUEST['mid'][$i];
$slno1 = mysql_real_escape_string(stripslashes($_REQUEST["slno1"][$i]));
$name1 = mysql_real_escape_string(stripslashes($_REQUEST["name1"][$i]));
$rhof1 = mysql_real_escape_string(stripslashes($_REQUEST["rhof1"][$i]));
$dob1 = mysql_real_escape_string(stripslashes($_REQUEST["dob1"][$i]));
$dobapt1 = mysql_real_escape_string(stripslashes($_REQUEST["dobapt1"][$i]));
$doc1 = mysql_real_escape_string(stripslashes($_REQUEST["doc1"][$i]));
$doconf1 = mysql_real_escape_string(stripslashes($_REQUEST["doconf1"][$i]));
$qualification1 = mysql_real_escape_string(stripslashes($_REQUEST["qualification1"][$i]));
$school1 = mysql_real_escape_string(stripslashes($_REQUEST["school1"][$i]));
$occupation1 = mysql_real_escape_string(stripslashes($_REQUEST["occupation1"][$i]));
$run=mysql_query("UPDATE member SET
slno1='".$slno1."',name1='".$name1."',rhof1='".$rhof1."',dob1='".$dob1."',dobapt1='".$dobapt1."',doc1='".$doc1."',doconf1='".$doconf1."',qualification1='".$qualification1."' WHERE mid = '".$mid."' " ) or die(mysql_error());
}
}
Please use PDO so you won't have to escape strings and so your code gets simpler to read. Your query has too many quotes used and this alone can make it easy to fail. Please use following examples and this should help you succeed.
Basic PDO update:
https://www.w3schools.com/php/php_mysql_update.asp
Bind Params:
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
In your query you are using $_POST['mid'] instead of that you should use $mid which you are already reading as
$mid=$_REQUEST['mid'][$i];
As per my understanding UPDATE query is used to update a limited number of records if using the where condition. So the only way that I can think of is using an INSERT query with ON DUPLICATE KEY UPDATE clause. Try the below code:
for($i=0;$i<count($_REQUEST['mid']);$i++) {
$mid[] = $_REQUEST['mid'][$i];
$slno1[] = mysql_real_escape_string(stripslashes($_REQUEST["slno1"][$i]));
$name1[] = mysql_real_escape_string(stripslashes($_REQUEST["name1"][$i]));
$rhof1[] = mysql_real_escape_string(stripslashes($_REQUEST["rhof1"][$i]));
$dob1[] = mysql_real_escape_string(stripslashes($_REQUEST["dob1"][$i]));
$dobapt1[] = mysql_real_escape_string(stripslashes($_REQUEST["dobapt1"][$i]));
$doc1[] = mysql_real_escape_string(stripslashes($_REQUEST["doc1"][$i]));
$doconf1[] = mysql_real_escape_string(stripslashes($_REQUEST["doconf1"][$i]));
$qualification1[] = mysql_real_escape_string(stripslashes($_REQUEST["qualification1"][$i]));
$school1[] = mysql_real_escape_string(stripslashes($_REQUEST["school1"][$i]));
$occupation1[] = mysql_real_escape_string(stripslashes($_REQUEST["occupation1"][$i]));
}
$query = "INSERT INTO `member` (`mid`,`slno1`,`name1`,`rhof1`,`dob1`,`dobapt1`,`doc1`,`doconf1`,`qualification1`) VALUES ";
for ($i = 0; $i < count($mid); $i++) {
$query .= "('".$mid[$i]."','".$slno1[$i]."','".$name1[$i]."','".$rhof1[$i]."','".$dob1[$i]."','".$dobapt1[$i]."','".$doc1[$i]."','".$doconf1[$i]."','".$qualification1[$i]."')";
if ($i != (count($mid) - 1)) {
$query .= ',';
}
}
$query .= ' ON DUPLICATE KEY UPDATE `slno1` = VALUES(`slno1`), `name1` = VALUES(`name1`), `rhof1` = VALUES(`rhof1`), `dob1` = VALUES(`dob1`), `dobapt1` = VALUES(`dobapt1`), `doc1` = VALUES(`doc1`), `doconf1` = VALUES(`doconf1`), `qualification1` = VALUES(`qualification1`);';
$run=mysql_query($query) or die(mysql_error());
Hope This Helps.
I have a form with two radio buttons 'phone me' and 'collect keys'. In order for the user to only select one of the two options, the input name are the same for both. If the user selects the first radio button where the value is equal to yes, then update the below database field:
UPDATE survey_bookings_mainsite SET appointment_phone = 'Yes' WHERE ref = $ref
else if the second radio button where the value is equal to no, then update the below database field:
UPDATE survey_bookings_mainsite SET appointment_keys = 'Yes' WHERE ref = $ref
Issue:
The second query returns 'No' in the appointment_phone field and displays NULL in the appointment_keys field. What is supposed to happen is the appointment_phone field to display 'No' and the appointment_keys field to also display 'Yes'. I have tried to in the second IF-Statement to re-assign $appointment_phone to equal to look like this:
$appointment_phone = mysql_real_escape_string($_POST['appointment_keys']);
but that doesn't work.
include("config/cn.php");
if(isset($_POST['Submit'])){
// Use array_map to secure all POST values:
$_POST = array_map('mysql_real_escape_string', $_POST);
$ref = $_POST['ref'];
$property_number = $_POST['property_number'];
$property_address1 = $_POST['property_address1'];
$property_address2 = $_POST['property_address2'];
$property_town = $_POST['property_town'];
$property_postcode = $_POST['property_postcode'];
$appointment_phone = $_POST['appointment_phone'];
$appointment_contact_number = $_POST['appointment_contact_number'];
$appointment_keys = $_POST['appointment_keys'];
if($_POST['appointment_phone'] == 'Yes'){
$sql = mysql_query("UPDATE survey_bookings_mainsite SET appointment_phone = 'Yes' WHERE ref = $ref");
}
if ($_POST['appointment_phone'] == 'No'){
$sql = mysql_query("UPDATE survey_bookings_mainsite SET appointment_keys = 'Yes' WHERE ref = $ref");
}
$collect_number = $_POST['collect_number'];
$collect_postcode = $_POST['collect_postcode'];
$collect_address1 = $_POST['collect_address1'];
$collect_address2 = $_POST['collect_address2'];
$collect_town = $_POST['collect_town'];
$collect_phone = $_POST['collect_phone'];
$report_name = $_POST['report_name'];
$report_number = $_POST['report_number'];
$report_address1 = $_POST['report_address1'];
$report_address2 = $_POST['report_address2'];
$report_town = $_POST['report_town'];
$report_postcode = $_POST['report_postcode'];
$report_phone = $_POST['report_phone'];
$report_email = $_POST['report_email'];
$special_instructions = $_POST['special_instructions'];
$enter_sql = "INSERT INTO survey_bookings_mainsite (ref,property_number,property_address1,property_address2,property_town,property_postcode,appointment_phone,appointment_contact_number,collect_number,
collect_address1,collect_address2,collect_town,collect_postcode,collect_phone,report_name,report_number,report_address1,report_address2,report_town,
report_postcode,report_phone,report_email,special_instructions)
VALUES(\"$ref\",\"$property_number\",\"$property_address1\",\"$property_address2\",\"$property_town\",
\"$property_postcode\",\"$appointment_phone\",\"$appointment_contact_number\",\"$collect_number\",\"$collect_address1\",\"$collect_address2\",\"$collect_town\",\"$collect_postcode\",
\"$collect_phone\",\"$report_name\",\"$report_number\",\"$report_address1\",\"$report_address2\",\"$report_town\",\"$report_postcode\",\"$report_phone\",\"$report_email\",\"$special_instructions\")";
$enter_query = mysql_query($enter_sql);
header('Location: /thankyou.php');
exit;
}
Your problem is that your two if-statements will never run both, one will work on yes and one will work on no. You have to combine them into 1 query:
$query = "UPDATE survey_bookings_mainsite SET
appointment_phone = '".($_POST['appointment_phone']=='Yes' ? 'Yes' : 'No')."' ,
appointment_keys = '".($_POST['appointment_phone']=='No' ? 'Yes' : 'No')."'
WHERE ref = $ref LIMIT 1";
$sql = mysql_query($query);
I took the liberty of adding LIMIT 1, if you only have to update 1 line, this will increase speed significantly when there is more load :)
The code in the query is short if/else, or ternairy. The following does exactly the same
if( $var === true ){ echo 'yes';}
else{ echo 'No';}
echo $var ===true ? 'yes' : 'no';
You method could actually work (though I strongly recommend you don't do the following!):
// Same code, simplefied for example:
if($_POST['appointment_phone'] == 'Yes'){
$sql = "UPDATE table SET appointment_phone = 'Yes',appointment_keys='No'";
}
if ($_POST['appointment_phone'] == 'No'){
$sql = "UPDATE table SET appointment_phone = 'No',appointment_keys='Yes'";
}
You dont want this because now you have two queries doing almost the exact same thing. What if you want to switch to 1/0 instead of yes/no? You would have to switch two queries (twice the room for error).
Just imagine what would happen if you have 10 inputs like this.
I'd like to check if a value is already in the table.
The structure of my table is this:
ApplicantId = INT
EventId = INT
StudentId = INT
No need to use unique because these table has dependencies.
Below is what I have tried so far:
include('../connectdb.php');
$ScholarPointId = $_GET["ScholarPointId"];
$Point = $_GET["Point"];
$ScholarId = $_GET["ScholarId"];
$EventId = $_GET["EventId"];
$verifysql = mysql_query("SELECT EventId FROM scholar_attended_events WHERE ScholarId ='$ScholarId' ");
#$resultVerify = mysql_fetch_assoc($verifysql);
$num_rows = mysql_num_rows($verifysql);
if( $num_rows > 0 )
{
$script = "<script>
alert('The user has already attended this event!');
</script>";
header('updatescholarpoints.php');
exit();
}
else{
$result = mysql_query("UPDATE scholar_points
SET scholar_points.Points =
scholar_points.Points + $Point
WHERE scholar_points.ScholarPointId = '$ScholarPointId' ") or die(mysql_error());
mysql_query("INSERT INTO scholar_attended_events (EventId , ScholarId) VALUES( '$EventId' , '$ScholarId' ) ")
or die(mysql_error());
}
?>
What I want is to check if the EventId is already in taken by the Student = StudentId. If so, then system will prompt an alert box. Otherwise, Update and Insert into respective table. How can I do this? It seems I miss something in here. If you could help, I really appreciate it.
just missing an = ?
$verifysql = mysql_query("SELECT EventId FROM scholar_attended_events WHERE ScholarId =$ScholarId ");
(and use PDO or mysqli, your code is really in a deprecated mode)
Before you assume I didn't establish a database connection, I did. the only portion of the code that does not update is the if empty statements.
All the values can be echoed out correctly, it's just that query doesn't work.
This is in directory config and named stuff.php
$user = $mysqli->real_escape_string($_SESSION['username']);
$user_query = "SELECT * FROM users WHERE username = '$user'";
$result = $mysqli->query($user_query);
$row = $result->fetch_assoc();
$referrer = $row['ref'];
$refearn = $row['refearn'];
verify.php
include('config/stuff.php');
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { // Get Real IP
$IP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$IP = $_SERVER['REMOTE_ADDR'];
}
if ($IP=="external server ip here") {
if (!empty($referrer)){
$mysqli->query("UPDATE users SET points=points+10, refearn = refearn+10 WHERE username='".$referrer."'") or die(mysqli_error($mysqli));
}
$mysqli->query("UPDATE users SET points=points+".$earnings.", completed = completed+1 WHERE username='".$subid."'") or die(mysqli_error($mysqli));
}
My guess is you could try to retrieve the value of points through a query then add to it so you're just updating to a simple value. However, if mysql_error() is returning an error, it should be easier to figure out.
Example:
$getPoints = mysql_query("SELECT points FROM table WHERE condition");
$points = mysql_result($getPoints, 0, "points");
$update = mysql_query("UPDATE table SET points=" . ($points+10) . " WHERE condition");
Hope that helps. Another consideration, though. Why use an endif structure unless you're breaking PHP tags to display content?
try this:
$mysqli->query("UPDATE `users` SET `points`=`points`+10, `refearn` = `refearn`+10 WHERE `username`='".$referrer."'") or die(mysqli_error($mysqli));
Hope this helps. What I think is, mysql query might be taking those as constant - not as the mysql rows. Try that
I am creating a browser statistics script in PHP.
When PHP finds a match in a table how do I retrieve the row and pull all three fields of the table into separate variables.
My table rows are (browser, version, amount)
so I want to select everything from the TB were
browser = $browser and version = $version.
But when this happens how do I add one to the amount field and resubmit the row. Without altering anything else. Below is the code I have.
$browser_name= "MSIE";
$version = "7";
$query = ("SELECT * FROM $TB
WERE browser = '$browser_name' AND version = '$version'");
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count == 1)
{
$mysql = ("SELECT * FROM $TB
WERE browser = '$browser_name' AND version = '$version'");
//code to add 1 to amount would be here
}
else
{
//if browser is not detected insert fresh row.
$mysql = "INSERT INTO $TB (browser, version, amount)
VALUES ('$browser_name', '$version', 1)";
}
I have been looking around for answers for ages but they just tell me how to select information out of a DB as a whole.
update table set amount_field = amount_field + 1 where browser = '$browser_name' and version = '$version'
I don't understand why you make twice the same select.
$browser_name= "MSIE";
$version = "7";
$query = "SELECT * FROM $TB WHERE browser = '$browser_name' AND version = '$version'";
$result = mysql_query($query);
if($data = mysql_fetch_assoc($result))
{
print_r($data);
//use UPDATE from other answers if you need one here.
}
else
{
//if browser is not detected insert fresh row.
mysql_query("INSERT INTO $TB (browser, version, amount)
VALUES ('$browser_name', '$version', 1)");
}
Beware of SQL injections!
SELECT * FROM $TB WHERE browser
you have a mistake it must be WHERE instead of WERE.
You update query will be like this
UPDATE $TB SET ammount = 1 WHERE browser = $browser and version = $version
There are hundreds of issues with your query like sanitization etc. I suggest you read a good mySQL book to improve the queries. But to answer your question:
//code to add 1 to ammount would be here
mysql_query("update $TB set amount = amount + 1 where browser = '".mysql_real_escape_string($browser_name)."' and version = '".mysql_real_escape_string($version)."'");
First of all, you should connect to db using
$db = new mysqli('host','user','pass','dbname');
Then, your query isn't right. You have a sql syntax error.
SELECT * FROM table WHERE column = value
So, without prepare, your code should look like:
$tb = 'table_name'; // to avoid sql injections use addslashes() to your input
$browserName = addslashes('browser_name'); // like this
$version = '7';
$db = new mysqli('host','user','pass','dbname');
$result = $db->query("SELECT * FROM $tb WERE browser = '$browserName' AND version = '$version'");
// Than, you can fetch it.
while ($result->fetch as $row) {
echo $row['yourColumn']; // will display value of your row.
}
$db->query("INSERT INTO $tb (browser, version) VALUES ('$browser_name', '$version')";
}");
And, that's all. You can count your records using mysql count() method. Your code will work. I advice you, at first go to php.net and check the doc. There are many examples.