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.
Related
I'm trying to write a query to check which column to update. The user sends an action which they performed (a like or a comment) and I'm trying to update a table. Is it possible to check inside the query which column to update? For example:
DB structure:
id imageName imageLikesCount imageCommentsCount
$actionPerformed = "like";
mysqli_query($link, "UPDATE table (if $actionPerformed=like SET imageLikesCount+1
else imageCommentsCount+1)
WHERE imageName='$image'");
I'm not sure how to phrase that, if it's possible at all. Any advice? Thanks in advance!
though meverhart913 has a way to do it, the better way to do the same thing is to instantiate your variable based on the if condition, then just plug that variable into your string. This keeps you from having to repeat your string over and over as well as allows you to easily add additional conditions.
if($actionPerformed=="like"){
$col = imageLikesCount;
else{
$col = imageCommentsCount;
}
mysqli_query($link, "Update table SET '$col' = '$col + 1' where imageName = '$image'");
if($actionPerformed=="like"){
mysqli_query($link, "Update table SET imageLikesCount = imageLikesCount + 1 where imageName = '$image'");
}
else {
mysqli_query($link, "Update table SET imageCommentsCount = imageCommentsCount + 1 where imageName = '$image'");
}
I'm not a php programmer so my syntax won't be correct, but here are two ways to do it:
if ($actionPerformed == "like")
query for updating imageLikesCount
else if ($actionPerformed == "comment")
query for updating imageCommentsCount
else
whatever
Or
if ($actionPerformed == "like")
$column = "imageLikesCount";
else ($actionPerformed == "comment")
$column = "imageCommentsCount";
$sql = "update table set $column = $column + 1";
Then execute it.
i am using this script to count how many rows exist in my table that have completed columns like so
<?php include 'config.php';
$q = "SELECT * FROM supplier_session WHERE form1_completed = 'Yes' AND form2_completed = 'Yes' AND form3_completed = 'Yes' AND form4_completed = 'Yes'" or die (mysql_error());
$result = mysql_query($q);
$count = mysql_num_rows($result);
?>
<?php echo "(<font color=red>$count</font>)"; ?>
this script says that if 'form1_completed, form2_completed, form3_completeed and form4_compelted all = 'yes' then to count the number of rows.
Now what i want to do, is have a seperate count that shows the number of rows that are incomplete, so baring in mind that some rows may only have 'form1_completed' as 'yes' and 'form2_completed' as 'no'. i need to basically count any rows that do not have all four columns completed or set as yes, so 'form1_complted', 'form2_completed', 'form3_completed', 'form4_completed' if these are not all yes then to count the rows
could someone please show me how i can do this? thanks
Try using conditional aggregation:
SELECT sum(form1_completed = 'Yes' AND form2_completed = 'Yes' AND
form3_completed = 'Yes' AND form4_completed = 'Yes'
) as NumAllCompleted,
sum(not (form1_completed = 'Yes' AND form2_completed = 'Yes' AND
form3_completed = 'Yes' AND form4_completed = 'Yes'
)
) as NumIncomplete
FROM supplier_session;
This assumes that the completed flags never take on NULL values.
Note: it is usually a bad idea to store "arrays" over values in multiple columns. You should have a junction/association table for each form. This would have one row for user/form combination, along with the status of that form. And it might have other information such as the date/time the form was completed.
If the fields do contain NULL values (say for when they haven't completed the form you could select everything and loop it as shown below though I would make the fields default to No and use Gordon Linoff answer myself.
<?php include 'config.php';
$q = "SELECT * FROM supplier_session" or die (mysql_error());
$result = mysql_query($q);
$count = mysql_num_rows($result);
$completed = 0;
foreach($result as $check) {
if(($check['form1_completed'] = 'Yes') && ($check['form2_completed'] = 'Yes') && ($check['form3_completed'] = 'Yes') && ($check['form4_completed'] = 'Yes')) {
$completed++;
}
}
$count // Total
$completed // Completed
$incomplete = $count - $completed; // Not Completed
echo "(<font color=red>$count</font>)";
?>
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 = ''
I have been trying to do this for hours now, and I can't quite get my head round it. I have a table called "requests" that has the columns "deletekey" and "deleted". "deletekey" is a random unique number (data-type text), and "deleted" is by default set to 0 (data-type boolean), and when the user inputs the deletekey, it changes "deleted" to 1.
But I can't get it to work.
Here is the code I have, and I have no idea what I'm doing wrong:
$key = $_GET["delkey"];
$link = mysqli_connect("localhost","username","password","dbname");
$query = 'UPDATE requests SET deleted = True WHERE deletekey = "$key"';
$result = $link->query($query);
This should help, and will also provide protection against SQL injection:
$link = mysqli_connect("localhost","username","password","dbname");
$key = $link->real_escape_string($_GET["delkey"]);
$query = sprintf("UPDATE requests SET deleted = 1 WHERE deletekey = '%s'", $key);
$result = $link->query($query);
Shouldn't it be WHERE deletekey = '$key', then? The deleted field could NEVER equal whatever's in $key, since deleted is a simple boolean, and $key is probably an int/char/varchar-type thing.
Note that you are vulnerable to SQL injection attacks. Stop working on this sort of code until you've learned about the problem and how to avoid it.
Its deletedkey = "$key" right ? and not deleted = "$key" :
$key = $_GET["delkey"];
$link = mysqli_connect("localhost","username","password","dbname");
$query = 'UPDATE requests SET deleted = true WHERE deletedkey = "$key"';
$result = $link->query($query);
Try this?
$link = mysqli_connect("localhost","username","password","dbname");
$key = $link->real_escape_string($_GET["delkey"]);
$query = "UPDATE `requests` SET `deleted` = true WHERE `deletedkey` = $key";
$result = $link->query($query);
$query = 'UPDATE requests SET deleted = 1 WHERE deletekey = "$key"';
the query is a string. And to add a variable to a string you need to type
$query = 'UPDATE requests SET deleted = True WHERE deleted = '".$key."';
the difference is how to make a variable put into the string. You have to do like this in php.
$query = "randomtext ". $randomvar ." ";
where the important point is to ". $var ." inside the string. This i similar to javas "+ var +"
I'm trying to update a database field with a 1 or 0, depending on whether a checkbox is checked or not.
It seems to work when the checkbox is checked but not when empty.
Any ideas how to solve this? Code below. Many Thanks, S.
Here's the code within my form:
$query = "SELECT * FROM istable WHERE assocProp = '".$_POST['id']."'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo '<li>
<label for="changePP'.$row['id'].'"><input id="changePP'.$row['id'].'" type="checkbox" name="showPP_ids[]" value="'.$row['id'].'"'.($row['showPP']=='1' ? ' checked="checked"':NULL).' /> Display</label>
</li>'. PHP_EOL;
}
And the php process code (updated):
$newQuery=mysql_query("select * from ispdfs where assocProp = '".$_POST['id']."'");
$newResult=mysql_fetch_array($newQuery);
foreach ($newResult as $showPP_ids) {
$val = (int) isset($_POST['showPP_ids']);
mysql_query("UPDATE ispdfs SET showPP = $val WHERE id = ".mysql_real_escape_string($showPP_ids));
}
You have nothing here that sets the values to zero. Boxes that are not checked will simply be absent from the $_POST array.
You'll need to make a separate list of the names of all of the checkboxes and cycle through those, comparing them against the $_POST array.
Edit: Wasn't going to write any code, but:
$allids = array('id1','id2','id3');
foreach ($allids as $oneid) {
$val = (int) isset($_POST[$oneid]); // will be 0 or 1
mysql_query("UPDATE istable SET showPP = $val WHERE id = ".mysql_real_escape_string($oneid));
}
Note that we don't really need the mysql_real_escape_string here since we know that all the id values are safe, but it's good practice just in case someone comes along later and carelessly changes the $allids array.
Edit again: Suppose we don't know what ids to look for.
mysql_query("UPDATE istable SET showPP = 0");
foreach ($_POST as $oneid=>$nothing) {
mysql_query("UPDATE istable SET showPP = 1 WHERE id = ".mysql_real_escape_string($oneid));
}
Probably your checkbox value doesn't get sent when it's not checked. Confirm this by print_r($_POST) in your php code.
Because of this, your condition
if (isset($_POST['showPP_ids'])) {
foreach ($_POST['showPP_ids'] as $showPPId) {
will never find a checkbox that wasn't checked.
As awm says correctly (+1 to that), you don't set the field showPP to 0. Do this:
$ppsql=mysql_query("UPDATE istable SET showPP = '0' WHERE id = ".mysql_real_escape_string($showPPId));
when you want to set your sql field to 0.
Since your checkbox won't be sent when it's not checked, you need to have some more information on which checkboxes to expect.
You could do (reusing your query code)
$query = "SELECT * FROM istable WHERE assocProp = '".$_POST['id']."'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$found = false;
foreach($_POST['showPP_ids'] as $showPPId)
{
if($showPPId == $row['id'])
{
// checkbox found
$found = true;
break;
}
}
$ppsql=mysql_query("UPDATE istable SET showPP = '"
.($found ? '1' : '0')
."' WHERE id = ".mysql_real_escape_string($showPPId));
}
An alternative would be JavaScript: Provide either two checkboxes and set the "not"-checkbox to true if the other one gets unchecked or use an <input type="hidden"> and change its value when the checkbox gets changed. If you have questions to this method, leave a comment - I've used that some times before...
another approach
Staying with your code, you could use this simple approach (but please don't...):
// first, set all fields to zero
/* long version
$query = "SELECT * FROM istable WHERE assocProp = '".$_POST['id']."'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$ppsql=mysql_query("UPDATE istable SET showPP = '0' WHERE id = ".$row['id']);
}
*/
// or short version:
$ppsql=mysql_query("UPDATE istable SET showPP = 0");
// now, update these rows that appear in `$_POST['showPP_ids']`
// (using the code you provided)
if (isset($_POST['showPP_ids'])) {
foreach ($_POST['showPP_ids'] as $showPPId) {
$ppsql=mysql_query("UPDATE istable SET showPP = '1' WHERE id = ".mysql_real_escape_string($showPPId));
}
}