Related
I am having issues when I untick a checkbox and leave it blank and update my PHP / MySQL form, the data is not saved in the database. Updates text / date fields are working fine.
Code
$learning_opportunities = isset($_POST['learning_opportunities']) ? $_POST['learning_opportunities'] : $contact['learning_opportunities'];
$stmt = $pdo->prepare('UPDATE contacts SET current_living_situation=?, personal_strengths=?, skills_training=?, currently_spend_time=?,personal_goals=?,housing_situation_transport_childcare=?,
learning_actual_end_date=?, partcipant_complete_course=?, withdrawal_reason=?,participant_intended_learning=?,pcp_education=?,
coursestart_date=?,education_provider_name=?,course_title=?,course_level=?,planned_glh=?,in_paid_employment=?,in_paid_employment_start_date=?,
in_paid_employer_name_address=?,in_paid_job_title=?,in_paid_contracted_hour=?,not_in_paid_employment=?,pcp_gap_year=?,
pcp_others=?,pcp_voluntary_work=?,destination_progression_date=?,destination_progression_collection_date=?,project_officer_name=?,
project_officer_signature=?,project_officer_date=?,participant__name=?,participant__signature=?,participant__date=?,
final_assessment_progress_you_made=?,final_assessment_progress_your_goal=?,final_assessment_progress_your_reach_goal=?,
final_assessment_progress_overall=?,final_assessment_participat_name=?,final_assessment_participat_signature=?,
final_assessment_participat_date=?,final_assessment_project_worker_name=?,final_assessment_project_worker_signature=?,
final_assessment_project_worker_date=?,learning_opportunities=?,contact_for_other_purposes=?,empowering_communities=?,empowering_communities_name=?,empowering_communities_sign=?,empowering_communities_date=?,
participant_enrolled_onto=?,participant_moved_another_provider=?,participant_eligible_free_school=?,british_passport=?,
eec_passport=?,euss_via_home=?,preferred_evidence=?,provide_preferred_evidence=?,option_adoption_vertificate=?,option_driving_licence=?,
option_non_eu_passport=?,option_biometric_immigration=?,option_current_immigration=?,option_marriage_civil_partnership=?,
option_other_evidence=?,option_nine=?,details_evidence_provided=?,dwp_job_centre_letter=?,confirmation_relevant_organisation=?,self_certification_evidence=?,
partcipant_told_support=?,participant_file_completed_remotly=?,declaration_name_please_print=?,declaration_job_title=?,declaration_organisation=?,
declaration_signature_date=?,declaration_signature=? where id = ?');
$result = $stmt->execute([$current_living_situation,$personal_strengths,$skills_training,$currently_spend_time,$personal_goals,
$housing_situation_transport_childcare,$learning_actual_end_date,$partcipant_complete_course,$withdrawal_reason,$participant_intended_learning,$pcp_education,
$coursestart_date,$education_provider_name,$course_title,$course_level,$planned_glh,$in_paid_employment,$in_paid_employment_start_date,
$in_paid_employer_name_address,$in_paid_job_title,$in_paid_contracted_hour,$not_in_paid_employment,$pcp_gap_year,$pcp_others,
$pcp_voluntary_work,$destination_progression_date,$destination_progression_collection_date,$project_officer_name,$project_officer_signature,
$project_officer_date,$participant__name,$participant__signature,$participant__date,$final_assessment_progress_you_made,
$final_assessment_progress_your_goal,$final_assessment_progress_your_reach_goal,$final_assessment_progress_overall,$final_assessment_participat_name,
$final_assessment_participat_signature,$final_assessment_participat_date,$final_assessment_project_worker_name,$final_assessment_project_worker_signature,
$final_assessment_project_worker_date,$learning_opportunities,$contact_for_other_purposes,$empowering_communities,$empowering_communities_name,$empowering_communities_sign,$empowering_communities_date,
$participant_enrolled_onto,$participant_moved_another_provider,$participant_eligible_free_school,$british_passport,
$eec_passport,$euss_via_home,$preferred_evidence,$provide_preferred_evidence,$option_adoption_vertificate,$option_driving_licence,
$option_non_eu_passport,$option_biometric_immigration,$option_current_immigration,$option_marriage_civil_partnership,$option_other_evidence,$option_nine,
$details_evidence_provided,$dwp_job_centre_letter,$confirmation_relevant_organisation,$self_certification_evidence,$partcipant_told_support,
$participant_file_completed_remotly,$declaration_name_please_print,$declaration_job_title,$declaration_organisation,$declaration_signature_date,
$declaration_signature, $_POST['id']]);
if($result == true){
$details = "<b>All Data Updated</b>";
// Insert new record into the contacts table
$stmt = $pdo->prepare('INSERT IGNORE INTO client_activity (id,client_id,date,time,details,username) VALUES (?,?,?,?,?,?)');
$client_activity = $stmt->execute([ null,$_POST['id'],date("Y/m/d"),date("H:i:s"),$details,$_SESSION['name'] ]);
if($client_activity == true){
$msg = 'Updated Successfully!';
Form code
<input type="checkbox" name="learning_opportunities" value="learning_opportunities" <?php if($contact['learning_opportunities']=="Yes"){ echo 'checked'; } ?>> About courses or learning opportunities.<br>
I have read countless articles and tutorials and can't get it to update the data.
The assignment of the variable $learning_opportunities does not make any sense at all.
Only checked checkboxes are sent to the server.
The following snippet will just force the checkbox to be set back to true if the old value $contact['learning_opportunities'] was already true, making it impossible to uncheck the checkbox
$learning_opportunities = isset($_POST['learning_opportunities']) ? $_POST['learning_opportunities'] : $contact['learning_opportunities'];
If you want to be able to update that field you just need this assignment:
$learning_opportunities = isset($_POST['learning_opportunities']) ? 1 : 0;
After sending the form with the checkboxes keep in mind, that there are 2 scenarios possible:
if you checkbox was checked you will get "on" in $_POST['learning_opportunities'].
if your checkbox wasn't checked you will not get 'learning_opportunities' index in the $_POST array at all
Check this demo:
index.php
<?php
$contact['learning_opportunities'] = isset($_POST['learning_opportunities']) ? "yes" : "no";
?>
<form action="index.php" method="POST">
<input type="checkbox" name="learning_opportunities" <?= $contact['learning_opportunities'] === "yes" ? 'checked' : "" ?>>
About courses or learning opportunities.
<br>
<input type="submit" value="Submit">
</form>
I have a form which has select options for age and radiobuttons for gender. The idea is that the form can be used to search for a specific user by age and gender.
Currently, the form sometimes executes the header (see below) and sometimes not. So Assume, I am logged in as Conor, Conor specifies that he wants to search for a user aged between 20-21 and is male. Upon clicking submit, sometimes the form will find someone, sometimes it will not. I want the query to keep running until a user is found, unless no one exists in the database.
In this case, the header should be executed, taking the user to messages.php because a male aged 20 exists in the database.
Here is my approach:
Form:
<form action="random_chat.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="age_from" id="age_from" value="0"/>
<input type="hidden" name="age_to" id="age_to" value="50"/>
<label for="amount">Age:</label>
from:
<select name="age_from" id="age_a" onchange="checkages_a()">
<option value="none"></option>
<?php
for($i = 17; $i <= 50; ++$i) {
echo "\t", '<option value="', $i. '">', $i, '</option>', "\n";
}
?>
</select>
to:
<select name="age_to" id="age_b" onchange="checkages_b()">
<option value="none"></option>
<?php
for($i = 18; $i <= 50; ++$i) {
echo "\t", '<option value="', $i, '">', $i, '</option>', "\n";
}
?>
</select>
<!-- I have input type submit above the radio buttons due to table layout -->
<input type="submit" class="btn btn-info" name="submit" value="Click to start chat! " />
<label for="amount">Gender:</label>
<input type="radio" name="gender" value="male">Male</input> <br />
<input type="radio" name="gender" value="female">Female</input><br />
<input type="radio" name="gender" value="any">Any</input>
</form>
PHP code processing the form:
<?php
$refined_gender = htmlentities (strip_tags(#$_POST['gender']));
$age_from = htmlentities (strip_tags(#$_POST['age_from']));
$age_to = htmlentities (strip_tags(#$_POST['age_to']));
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (isset($_POST['submit'])){
// if age parameter used...
$defined_chat = mysqli_prepare ($connect, "SELECT * FROM users WHERE gender =? AND age BETWEEN ? AND ? ORDER BY RAND() LIMIT 1");
mysqli_stmt_bind_param($defined_chat, "sss", $refined_gender, $age_from, $age_to);
mysqli_stmt_execute ($defined_chat);
while ($get_user = mysqli_fetch_assoc($defined_chat)){
$rand_name = $get_user['username'];
$acc_type = $get_user['account_type'];
if ($acc_type != "admin" ){
// if the name genereated by db is same as logged in users name, then run query again until name is found.
if ($rand_name == $username){
$defined_chat;
} else {
header ("Location: /messages.php?u=$rand_name");
}
} else {
echo "No user found fitting those requirements.";
}
} // while closed
mysqli_stmt_close($defined_chat);
}
?>
I have tried to change the form action to '#', thinking it may be just be refreshing the page, but it didn't work.
Also, how can I make this so that even if one parameter is filled, then still execute search? For example, if I search for a male, with no age defined, it will find a male user. If I search for someone ages between 26-31 and no gender defined, then still execute header?
Edit:
$username is the session variable, which is defined at the very start of random_chat.php.
Do not rely on the value of a submit button to determine if your form was submitted or not. This will not work on all browsers, especially older ones, this value is not always passed back to the server, instead just look at any value inside the form to verify if submission has occurred, or the existence of $_POST in general.
At first sight, what you are attending to do looks to me simpler than the way you are actually trying to achieve it.
Construction you SQL query correctly may be the only thing complicated in here.
Only changing your query could actually already remove your need of the if/else for the account_type and the if/else to check if the current user is the same as the queried one :
$sql = "SELECT
*
FROM
users
WHERE
gender like ? AND
age BETWEEN ? AND ? AND
# with this condition you do not need to test if the user logged is the queried one
username != ? AND
# and with this one, you do not care about exclude adimn either
account_type != 'admin'
ORDER BY RAND()
LIMIT 1";
$defined_chat = mysqli_prepare (
$connect, $sql
);
mysqli_stmt_bind_param(
$defined_chat,
"ssss",
$refined_gender,
$age_from,
$age_to,
$username
);
Then about the fact that you want to be able to search even without any selection on both gender and age, you can use a combinaison of the wildcard % of SQL, the operator like and the ternary operator of PHP (you did maybe already see that I changed gender =? to gender like ? in the query above).
// Means if gender is different than 'any', it will assign the posted value to the variable, otherwise, it will assign the sql wildcard %
$refined_gender = (htmlentities (strip_tags(#$_POST['gender'])) != 'any' ? htmlentities (strip_tags(#$_POST['gender'])) : '%');
// Means if age is different than 'none', it will assign the posted value to the variable, otherwise, it will assign the lowest possible age, 0
$age_from = (htmlentities (strip_tags(#$_POST['age_from'])) != 'none' ? htmlentities (strip_tags(#$_POST['age_from'])) : '0');
// Means if age is different than 'none', it will assign the posted value to the variable, otherwise, it will assign an age bigger than anyone could attain, 9999
$age_to = (htmlentities (strip_tags(#$_POST['age_to'])) != 'none' ? htmlentities (strip_tags(#$_POST['age_to'])) : '9999');
see ternary operators in PHP doc
and see MySQL like and wildcard usage
All in one, your processing PHP script could look like this :
$refined_gender = (htmlentities (strip_tags(#$_POST['gender'])) != 'any' ? htmlentities (strip_tags(#$_POST['gender'])) : '%');
$age_from = (htmlentities (strip_tags(#$_POST['age_from'])) != 'none' ? htmlentities (strip_tags(#$_POST['age_from'])) : '0');
$age_to = (htmlentities (strip_tags(#$_POST['age_to'])) != 'none' ? htmlentities (strip_tags(#$_POST['age_to'])) : '9999');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (isset($_POST['submit'])){
$sql = "SELECT
*
FROM
users
WHERE
gender like ? AND
age BETWEEN ? AND ? AND
# with this condition you do not need to test if the user logged is the queried one
username != ? AND
# and with this one, you do not care about exclude adimn either
account_type != 'admin'
ORDER BY RAND()
LIMIT 1";
$defined_chat = mysqli_prepare (
$connect, $sql
);
mysqli_stmt_bind_param(
$defined_chat,
"ssss",
$refined_gender,
$age_from,
$age_to,
$username
);
mysqli_stmt_execute ($defined_chat);
while ($get_user = mysqli_fetch_assoc($defined_chat)){
$rand_name = $get_user['username'];
header ("Location: /messages.php?u=$rand_name");
} // while closed
echo "No user found fitting those requirements.";
mysqli_stmt_close($defined_chat);
}
You have some mixed logic, so some explanations might help.
1) header('location: ...') will tell the browser to reload the page to the new location. This does not appear to be what you want - you just want to continue execution? NOTE: You should also [nearly] always have "exit();" after a header('location: ... '); line otherwise execution continues which is [nearly] never what you want!)
2) a while loop will continue "while" the condition is true. So the loop continues while there are rows being returned.
3) Running the query again will not return anything new - you can use the same results. So just skip over until you find the result you need!
So, written in English, what you want to do after running the DB query is:
set a tally count to zero
while we have some rows coming from the db {
if that row is not admin {
if that row does not match the current user {
show the result
increase tally count
}
}
}
if tally count is zero {
say "no entries found"
}
So, in code, this is
$foundUsers = 0;
while ($get_user = mysqli_fetch_assoc($defined_chat)){
$rand_name = $get_user['username'];
$acc_type = $get_user['account_type'];
if ($acc_type !== "admin" ){
// if the name genereated by db is same as logged in users name, then run query again until name is found.
if ($rand_name !== $username) {
$foundUsers = $foundUsers + 1; // Or $foundUsers++ for short
echo 'Matched User: ' . $rand_name . '<br>';
}
}
} // while closed
if ($foundUsers == 0) {
echo "No user found fitting those requirements.";
}
Ok, first of all, if you want to exclude a parameter from the query, you're going to have to build some logic to exclude that variable.
So if $refined_gender = "any", then you need to exclude it from the query. I would change your combobox default values to:
<select name="age_from" id="age_a" onchange="checkages_a()">
<option value="-1"></option>
<?php
for($i = 17; $i <= 50; ++$i) {
echo "\t", '<option value="', $i. '">', $i, '</option>', "\n";
}
?>
</select>
to:
<select name="age_to" id="age_b" onchange="checkages_b()">
<option value="999"></option>
<?php
for($i = 18; $i <= 50; ++$i) {
echo "\t", '<option value="', $i, '">', $i, '</option>', "\n";
}
?>
</select>
Then, now you've fixed the age between, to filter the gender out. Also, I've added a clause to your WHERE clause: AND account_type != 'admin', this will filter out the admins accounts on the SQL side rather than checking on the PHP side.
// If gender is specified, query gender
if($refined_gender !== "any"){
$defined_chat = mysqli_prepare ($connect, "SELECT * FROM users WHERE gender =? AND age BETWEEN ? AND ? AND account_type != 'admin' ORDER BY RAND() LIMIT 1");
mysqli_stmt_bind_param($defined_chat, "sii", $refined_gender, $age_from, $age_to);
} else {
$defined_chat = mysqli_prepare ($connect, "SELECT * FROM users WHERE age BETWEEN ? AND ? AND account_type != 'admin' ORDER BY RAND() LIMIT 1");
mysqli_stmt_bind_param($defined_chat, "ii", $age_from, $age_to);
}
mysqli_stmt_execute ($defined_chat);
Suggestion #1: Possible race condition see note in code.
if ($acc_type != "admin" ){
// if the name genereated by db is same as logged in users name, then run query again until name is found.
if ($rand_name == $username){
$defined_chat;<-- don't you need to re-execute this? Seems like you are hitting a race condition since the statement result will never change
} else {
header ("Location: /messages.php?u=$rand_name");
}
} else {
echo "No user found fitting those requirements.";
}
Suggestion #2:
Outside of that you should be sure you aren't getting the current user with a
WHERE name NOT LIKE '%?%' up front in the initial query and get rid of that if statement.
Suggestion #3:
Or better, use the user IDs. What if there's another user with the same name as the searcher, but they're a different person? Base the current user match on UID, not name.
Suggestion #4:
You should absolutely almost never run a select query/statment inside a PHP (or any scripting language) loop. There's always a better way. Filter your data in the database where it's efficient. Even for inserts you can do a single bulk insert much more efficiently than a bunch of insert queries.
im trying to update checkbox value into database. i already write some code and it worked updating the database..however for some reason i got undefined index in my combobox variable..here is my code..
code to display existing data into checkbox
<tr>
<td><label for="cbPin">Pin this post</label></td>
<td><input type="checkbox" name="cbPin" class="checkbox checkbox-warning" id="cbPin" <?php
if ($pin == 0) {
?> value="0" <?php
} else {
?> checked value="1" <?php
} ?>
/></td>
</tr>
this one is variable to render the form
$pin = $row[9];
and this one if button submit clicked
$pin = ($_POST['cbPin']);
if ($pin == '') {
$pinpost = 0;
} else {
$pinpost = 1;
}
and this is my query
if ($stmt = $mysqli->prepare("UPDATE tblanouncement SET title = ?, message = ?, pinpost = ? WHERE anouncementId=?"))
{
$stmt->bind_param("ssii",$title, $message, $pinpost, $id);
$stmt->execute();
$stmt->close();
A checked checkbox sends its name and value.
A non-checked checkbox is not a successful control and won't be submitted at all.
If you aren't dealing with multiple checkboxes of the same name, use isset to see if the data exists or not. Don't assume you will have a value for it in the POST data array.
If the checkbox ['transfer'] is checked which will be the default checkbox that displays on the page, after being saved and the page refreshes they should only have the option to view the checkbox ['reverse'].
If they select reverse and save the option for the checkbox ['transfer'] should appear again.
I'm trying to wrap my head around it and it seems really simple but i'm having a block atm.
so i created a variable for my sql query:
$secular = sql::value("select * from ev.do.taskAU where event_id = $event_id and transfer = '1'");
essentially both checkboxes will have the same field name in the database.. that will be ['transfer'] and it should change based on the bit 0 or 1.
hope that makes sense and any help would be greatly appreciated.
This is what i'm trying:
<?php
$secular = sql::value("select * from event.dbo.taskAU where event_id = $event_id and transfer = '1'");
$checked = $secular['transfer'];
?>
<table><tr>
<?php if ($checked == 1) echo "<td>Transfer</td><?php if (in_array(login::$id, array('02O','04R','0A3','0BN','0BO','00D','0FR','0E1'))) { echo <td>". cbox_return('transfer') ."</td>"; ?>
<?php if ($checked == 0) echo "<td>Reverse</td><?php if (in_array(login::$id, array('02O','04R','0A3','0BN','0BO','00D','0FR','0E1'))) { echo <td>". cbox_return('transfer') ."</td>"; ?></tr></table>
</tr></table>
Once you get the value of whether or not the item was checked from the database, you would use this code:
$checked = ('whatever value you got from the database');
$checkedValOne = (in_array(login::$id, array('02O','04R','0A3','0BN','0BO','00D','0FR','0E1'))) ? true : false;
$checkedValTwo = ($checked == 1 ? true : false;
<input type="checkbox" value="<?php echo (($checkedValOne && $checkedValTwo) ? "checked" : ""));?>" />
The above code will only add checked to the checkbox if the value from the database was 1.
I have 2 drop-down lists with different names, and I'm trying to query in just one field.
I'm using a jQuery function wherein if item 1 is selected, the drop-down list 1 will be displayed, and if the item 2 is selected, the drop-down list 2 will be displayed.
This is how I populated my drop-down list from the mysql database and tables:
<div id="minquep">
<label>Branch</label>
<SELECT name="user_min">
<OPTION VALUE="0">Choose a branch
<?=$minq_options?>
</SELECT>
</div>
<div id="albury">
<label>Branch</label>
<SELECT name="user_branch">
<OPTION VALUE="0">Choose a branch
<?=$al_options?>
</SELECT>
And this is how I insert queries into mysql by filling out the form with drop-down lists in it:
if (isset($_REQUEST['Submit'])) {
$sql = "INSERT INTO $db_table(branch) values ('".mysql_real_escape_string(stripslashes($_REQUEST['user_branch'])).",".mysql_real_escape_string(stripslashes($_REQUEST['user_min']))."')";
if($_REQUEST['user_branch']= ""){
($_REQUEST['user_branch']) = NULL;
}
if($result = mysql_query($sql ,$db)) {
echo '<script type="text/javascript">alert("The user has been added successfully!\n");return true;</script>';
echo "<meta http-equiv=\"refresh\" content=\"0;URL=add_user.php\">";
}
else {
echo "ERROR: ".mysql_error();
}
}
The testing scenario is that, I choose the value under <select name="user_min">.
So I assume that sql will just bypass the result for user_branch because it is null. But it does prints '0' instead, after the insert query. For example, if the inserted ($_REQUEST['user_min']) value is "Brisbane" and the ($_REQUEST['user_branch']) value is null (because I didn't selected any value under the user_branch drop-down list), the branch field should just become "Brisbane", knowing that user_branch is NULL. But it does print "BRISBANE" with 0, like 0, Brisbane in my mysql table.
How can I fix this?
I already tried putting an if condition, it did not work.
if($_REQUEST['user_branch']= ""){
($_REQUEST['user_branch']) = NULL;
}
I've also tried changing the user_min into same name user_branch, but it does not get the selected value, instead of Brisbane it just prints '0'
A few things -
you are setting user_branch = NULL after the $sql.
You are using quotes around value. It's fine non-Null values -you need to check if there is NULL value then don't use quotes in your $sql.
You are using single "=" in your IF statement. This is failing your If statement. Change it to if($var == '')
Update
Some suggestions based on your existing code - however there are other best practices to achieve what you are trying to achieve....
$user_branch = $_REQUEST['user_branch'];
$user_min = $_REQUEST['user_min'];
//you should validate above values first
if$user_branch == "" || $user_min == "") {
$db_value = "NULL";
} else
{
$db_value = "'".mysql_real_escape_string(stripslashes($user_branch.','.$user_min))."'";
}
$sql = "INSERT INTO $db_table(branch) values (".$db_value.")";
If you don't want 0, then change:
<option value="0">Chose a Branch</option>
To:
<option value="">Chose a Branch</option>
Otherwise it will get passed through the form as 0
Also, your PHP code won't work as you want it to:
if (isset($_REQUEST['Submit'])) {
// do this before the query
if($_REQUEST['user_branch']== ""){ // note the extra = in there, so you aren't assigning the variable, you are compairing
$_REQUEST['user_branch'] = NULL; // no need for brackets round the variable
}
$sql = "INSERT INTO $db_table(branch) values (".mysql_real_escape_string(stripslashes($_REQUEST['user_branch'])).",".mysql_real_escape_string(stripslashes($_REQUEST['user_min'])).")"; // you had single quotes around everything inside the VALUES() function
if($result = mysql_query($sql ,$db)) {
echo '<script type="text/javascript">alert("The user has been added successfully!\n");return true;</script>';
echo "<meta http-equiv=\"refresh\" content=\"0;URL=add_user.php\">";
}
else {
echo "ERROR: ".mysql_error();
}
}
$sql = "INSERT INTO reg(Name ,Email) values ('".mysql_real_escape_string(stripslashes($_REQUEST['Name']))."','".mysql_real_escape_string(stripslashes($_REQUEST['Email']))."')";
This is my code. Here I found error of Undefined index.