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));
}
}
Related
My variables in the mysql table are "usersEmail" "usersRefer and "usersPoint". I want to check the whole table if usersEmail = usersRefer on different rows then UPDATE the integer usersPoint on the row of both usersEmail and usersRefer. I want to check for one specific user, that is the value of the usersRefer checks the entire column of usersEmail to check if it matches.
Here's something that I tried out:
$sql = "SELECT * FROM walitlist";
if($result = $conn->query($sql)){
while ($row = $result->fetch_assoc()){
$pointSys = $row ["usersPoint"];
if ($row ["usersEmail"] = $row ["usersRefer"]){
$pointSys = "UPDATE waitlist SET usersPoint = usersPoint+100";
}
}
}
How can I make this work?
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 have a page that writes to a MySQL table. The table has a set amount of rows (24).
I have an $id variable that's set by a rand() function. I basically want to pull the row at that $id, so if $id was 3, I want to pull the third row. Then, I want to check if there is a price set at that row (indicating that the row is being used). If there is no price, I want to keep $id at the value it has been set at and proceed with the query. If there is a price, I want to re-randomize the $id variable, and check again if that row is used up. When it finds an empty row, proceed with the query.
My solution semi-works, but it seems to have a <10% chance of overwriting a used row, for some reason. I want it to never overwrite a used row.
Here's my code:
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet WHERE id = '$id'";
$res = mysql_query($query,$con);
$newId = $id;
while($row = mysql_fetch_array($res))
{
if($row['price'] != 0)
{
do{
$newId = rand(1, 24);
}while($newId == $id);
}
}
$id = $newId;
mysql_query("UPDATE booklet SET price = '$price', advertiser = '$advertiser', image = '$image', monthsRemaining = '$monthsRemaining', availability = 1 WHERE id = '$id'");
Edit
I had the idea to do this. I loop through the table and I put the 'id' of each unfilled spot into an array. Then I pick randomly from that array. However, there seems to be a bug that I can't find, since the array keeps showing as having nothing in it, even after the loop is run, and $i is the correct figure.
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet";
$res = mysql_query($query,$con);
$i = 0;
$isEmpty = array();
while($row = mysql_fetch_array($res))
{
if($row['price'] == 0)
{
$isEmpty[i] = $row['id'];
$i = $i + 1;
}
}
echo $i . " unfilled spots.";
$n = 0;
while($n<$i)
{
echo $isEmpty[$n];
$n = $n + 1;
}
if($i > 0)
{
$id = $isEmpty[rand(0, $i)];
}
if($i == 0)
{
echo 'All spots have been filled.';
}
I think it is a top level logic problem. Because you populate with random ids, you can get duplicate ids, and so when you update "WHERE id = '$id'" you may be picking up rows already populated.
I don't know your goal, but perhaps using an auto-increment id, and dropping rows that you want to get rid of, is the way to go. A rolling set of rows (24 at a time) but with ever increasing ids, would prevent mistaking one for the other.
If I understand the problem correct, this should work:
SELECT *
FROM booklet
WHERE price = 0 OR price IS NULL
ORDER BY RAND()
My checkbox looks like this:
<input type="checkbox" name="activate[]" class="setSetting" value="<?php echo $row["id"]; ?>">
And then i have a foreach:
$activate = $_POST['activate'];
foreach($activate as $a){
echo $a ."<br>";
}
Works fine to get the value out of. But how can i determine if the checkbox has been checked?
$activate = $_POST['activate'];
foreach($activate as $a){
$query_email = mysql_query("SELECT id FROM lp_email_settings ORDER BY id ASC");
while($ro = mysql_fetch_row($query_email)){
$getUserSettings = mysql_query("SELECT * FROM users_email_settings WHERE uID = '$USER' AND eSetting = '$ro[0]'");
if($ro[0] == $a){
if(mysql_num_rows($getUserSettings) != 1){
mysql_query("INSERT INTO users_email_settings (uID, eSetting) VALUES ($USER, $ro[0])");
}
}else{
mysql_query("DELETE FROM users_email_settings WHERE uID = '$USER' AND eSetting = '$ro[0]'");
}
}
echo $a."<br>";
}
Only those checkboxes will be submitted that are considered successful (i.e. checked). That means only the checked checkboxes are available in $_POST['activate'].
And to determine whether a checkbox has been checked, you can use array_search to check whether a particular ID value is in $_POST['activate']:
array_search('12345', $_POST['activate'], true)
And if you change your control’s name to use the ID as key like this:
<input type="checkbox" name="activate[<?php echo $row["id"]; ?>]" class="setSetting" value="<?php echo $row["id"]; ?>">
Then you can simply use isset or array_key_exists on $_POST['activate']:
isset($_POST['activate']['12345'])
array_key_exists('12345', $_POST['activate'])
Edit As already said in the comments, you should rather iterate the available options and check for each option whether it’s already active and needs to be activated or deactivated. You can do this as follows:
$activate = array_flip($_POST['activate']);
$query = "SELECT t1.id, t2.eSetting
FROM lp_email_settings t1 LEFT OUTER JOIN users_email_settings t2 ON (t1.id = t2.eSetting)
ORDER BY t1.id ASC";
$result = mysql_query($query);
$insert = array();
$delete = array();
while ($row = mysql_fetch_row($result)) {
if ($row[1] === null) {
// option is not set yet
if (isset($activate[$row[0]])) {
// option needs to be set
$insert[] = $row[0];
}
} else {
// option is already set
if (!isset($activate[$row[0]])) {
// option needs to be unset
$delete[] = $row[0];
}
}
}
if (!empty($insert)) {
$query = "INSERT INTO users_email_settings (uID, eSetting)
VALUES ($USER, " . implode("), ($USER, ", $insert) . ")";
mysql_query($query);
}
if (!empty($delete)) {
$query = "DELETE FROM users_email_settings
WHERE uID = $USER AND eSetting IN (" . implode(", ", $delete) . ")";
mysql_query($query);
}
The first query will select a left join of all available options and the already active options. So the result set is the ID of the option in the first column and the second column is either NULL if the options is not active or otherwise again the ID. So if there are three options (e.g. 1, 2, and 3) and only the options 1 and 3 are already set, the result should look like this:
id | eSetting
----+----------
1 | 1
2 | NULL
3 | 3
So if $row[1] is null (inactive option), the ID in $row[0] is added to the $insert array if the corresponding option was set in the request ($activate[$row[0]], the keys/values are flipped to have a direct access). The same is done for those options that are already active but were not set in the request.
At the end the collected options in $insert are inserted and those in $delete are removed.
If you get a value it has been checked, otherwise you get nothing...
Here is a pretty good tutorial explaining how it works: http://www.html-form-guide.com/php-form/php-form-checkbox.html
Checkboxes will only be submitted at all if they are ticked. If they are unticked, PHP won't see them in $_POST.
I assume since you're using square brackets (ie activate[]) that you have more than one of them all with the same name. This will make it very hard to tell which ones were ticked, since you'll just get an array of the ones which were ticked; you'll know how many, but not which ones.
To get around this, you either need to give them all different names, or specify the array key for each one in the HTML code - ie name="activate[4]" or name="activate[bob]". Depending on the context, this could be an ID of the data you're activating, or the name of the feature, or anything else you decide, as long as it's unique for each field.
You will then still get the array only containing the ones which were ticked, but you will be able to tell which ones they were in your foreach loop by looking at the array key.
Hope that helps.
You can check against each submitted value ($activate) to see if it does actually contain anything/fits your criteria:
$activate = $_POST['activate'];
foreach($activate as $a){
if($activate){
echo $a ."<br>";
}
}
Though the array should only contain those values checked.
I'm working in Drupal 6 with CCK. Under each text field there is a PHP section where you can run some PHP code to get allowed values. I'm running into trouble using an "if" statement to change the allowed values based on user type
So to start, I do a query to determine current users user type. -1 is default user, which is employees and user type id "1", is for site users. What I want is to restrict the site user to only the allowed values they need to see, while allowing employees to edit that value when on the node edit screen with all choices.
The first part of the if statement works. However, the "else" part doesn't work. Is this field set up to deal with control structures?
global $user;
$sql1 = "SELECT user_type_id FROM user_types_user WHERE uid = ".$user->uid." ";
$res1 = db_query($sql1);
if($res1 == '1'){
$sql = "SELECT account FROM users WHERE uid = ".$user->uid." ";
$res = db_query($sql);
while($row = db_fetch_array($res)){
$rows[] = $row['account'];
}
$rows = drupal_map_assoc($rows);
return $rows;
}
else {
$sql2 = "SELECT title FROM node WHERE type = 'accounts' ";
$res2 = db_query($sql2);
while($row2 = db_fetch_array($res2)){
$rows2[] = $row2['title'];
}
$rows2 = drupal_map_assoc($rows2);
return $rows2;
}
The choices are type=accounts in nodes, however, when a user is created one of the choices is selected and stored in the user table, under a column I created named "account"
If by 'the "else part does not work' you mean that it is never executed, even if user_type_id does not equal 1, it might be the missing db_fetch_array() on $res1. You're comparing your result object directly to the string '1', not the field value.
Here is the working code for this. There may have been a quicker/shorter way to do this.
global $user;
$sql1 = "SELECT user_type_id FROM user_types_user WHERE uid = ".$user->uid." ";
$res1 = db_query($sql1);
while($type = db_fetch_array($res1)){
$types[] = $type['user_type_id'];
}
$resType = $types[0];
if($resType == "1"){
$sql = "SELECT account FROM users WHERE uid = ".$user->uid." ";
$res = db_query($sql);
while($row = db_fetch_array($res)){
$rows[] = $row['account'];
}
$rows = drupal_map_assoc($rows);
return $rows;
}
else {
$sql2 = "SELECT title FROM node WHERE type = 'accounts' ";
$res = db_query($sql2);
while($row2 = db_fetch_array($res)){
$rows2[] = $row2['title'];
}
return $rows2;
}