Delete database entry if checkbox is unchecked - php

I have a form that allows engineers to be added to a job by checking checkboxes which works fine. However, I would like the user to remove an engineer by unchecking their checkbox on another form.
The table (a many to many table) has 3 columns id_ce (the primary key), call_ce (foreign key) and engineer_ce (foreign key). I would like the form to check if a checkbox is empty and if it is check to see if there is an entry in the table with the call_ce and engineer_ce and delete it if it exists but I'm failing miserably.
This is what I have so far...
foreach($_POST['engineer'] as $engineer_id){
if(!isset($_POST['engineer'])){
$sql = "SELECT * FROM calls_engineers WHERE call_ce = '$diary_id' AND engineer_ce = '$engineer_id'";
$result = mysql_query($sql)or die(mysql_error());
if(mysql_num_rows($result) > 0){
$sql = "DELETE FROM calls_engineers WHERE engineer_ce = '$engineer_id'";
$result = mysql_query($sql)or die(mysql_error());
}
}
}
I suspect the problem may be something like the checkboxes that aren't checked don't post so they aren't going through the foreach loop but I'm not sure of another way of doing it.
Any help will be greatly appreciated

You can put on page a hidden field with engineer ids. Say, it will be called engineer_on_page
Now you can
foreach($_POST['engineer_on_page'] as $engineer_id) {
if(!in_array($engineer_id, $_POST['engineer'])){
//do delete here
}
}
I expect that checkboxes looks similar to this:
<input type="checkbox" name="engineer[]" value="[engineer_id]"/>
and hidden field
<input type="hidden" name="engineer_on_page[]" value="[engineer_id]"/>
Also you may specify checkbox field like this:
<input type="checkbox" name="engineer[[engineer_id]]" value="[engineer_id]"/>
where [engineer_id] is actual id (1, 2,3 etc)
In second case you may use
if(!isset($_POST['engineer'][$engineer_id])){
//do delete here
}

/* BY ROHIT BHAYAL */
$checkbox1=$_POST['stu2'];
$chk="";
/* print_r($_POST['stu3']); */
$order1=$_POST['stu3'];
if(isset($_POST['subject']))
{
$string = implode(',', $checkbox1);
echo $del="delete from student_subject where sub_id not in ($string)";
mysql_query($del);
}
// mysql_query($del);
foreach ($checkbox1 as $key => $chk1)
{
$chk .= $chk1.",";
$check="SELECT * FROM student_subject WHERE sub_id = '".$chk1."' AND form_id='".$_GET['sub']."'";
$rs = mysql_query($check);
$data = mysql_fetch_array($rs);
mysql_num_rows($rs);
if($data[0] > 1)
{
echo "Subject is Already Exists<br/>";
}
else
{
if(isset($_POST['subject']))
{
$a= "sub_id='".$chk1."'";
echo $ins = "insert into student_subject set form_id='".$_POST['stu1']."',
".$a.",
order_no='".$chk1."'";
}
if (mysql_query($ins))
{
echo "Now New subject Is Added<br/>";
}
else
{
echo "Error adding user in database<br/>";
}
}
}
?>

Related

The best way to run completely unrelated queries together?

I seem to be running into this issue often, usually for checking to see if a $_GET['id'] actually exists in my database before running another query, related or not to the id being received.
If a record exists with the same id, then I show the HTML, e.g.:
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
?>
<form method="post">
...
<input type="submit" value="Submit" />
</form>
<?php
} else {
echo 'No records';
}
} else {
echo 'Query Failed';
}
mysqli_free_result($r);
The above works, but let's say that I want to perform another unrelated query between my opening/closing form tags; would it be proper to simply do something like this, which I would consider a nested query:
$q = "SELECT id FROM stuff WHERE id = $id";
$r = #mysqli_query($dbc, $q);
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
?>
<form method="post">
<?php
$q = "SELECT example FROM somewhere";
$r = #mysqli_query($dbc, $q);
if ($r) {
$num = mysqli_num_rows($r);
if ($num > 0) {
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo $row['example'];
}
}
} else {
echo 'Query failed';
}
?>
<input type="submit" value="Submit" />
</form>
<?php
} else {
echo 'No records';
}
} else {
echo 'Query Failed';
}
mysqli_free_result($r);
Or maybe create a boolean, like so:
$id_status = 0;
$q = "SELECT id FROM stuff WHERE id = $id";
$r = #mysqli_query($dbc, $q);
if ($r) { #query was successful
$num = mysqli_num_rows($r);
if ($num == 1) {
$id_status = 1;
}
}
mysqli_free_result($r);
if ($id_status) { #Run another query
...
}
I currently have a problem when it comes to requiring two separate query results for one task: (1) generating inputs from another table, (2) displaying the current values, (3) checking to see what input that has been generated matches the current value, e.g.:
$q = "SELECT id, food FROM restaurants";
$q = "SELECT favFood FROM people WHERE id = 1"; #favFood is equal to the id of food
...
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
?>
#generate all food from table, make favFood the current selected input
<input type="radio" name="yum" value="<?php echo $row['id']; ?>" />
<?php
}
So as you can see, I am having trouble when it comes to unrelated queries; the last example would probably work with a UNION or something, but i'd have a bunch of repeated rows displaying favFood, so it doesn't feel right, e.g.:
favFood | id | food
1 | 1 | Pizza
1 | 2 | Burgers
1 | 3 | Monkey Brains
Before I end this, I just want to say that I have made an attempt to use mysqli_multi_query, but I most likely did something wrong; i'm not even sure if it would work in this case, or what it does exactly.
Thanks!
If you want to check whether a record exists multiple times in your code, I suggest to create a function which returns a bool.
function record_exists($dbc, $q){
$state = false;
if($r = #mysqli_query($dbc, $q)){
if(mysqli_num_rows($r) == 1){
$state = true;
}
mysqli_free_result($r);
}
return $state;
}
$q = "SELECT id FROM stuff WHERE id = $id";
if(record_exists($dbc, $q)){
echo 'Yay, it exists';
}
Then if you want to SELECT some fields from a table but the filter depends on a value from another table, you could JOIN two tables in the query like so:
SELECT restaurants.id, restaurants.food
FROM restaurants
JOIN people ON restaurants.id = people.favFood
WHERE people.id = 1
Now you only SELECT the fields you want from table restaurants and filter them on a person id from the table people.
Two reasons why you've got such a problem
You are doing A LOT of useless stuff.
no one needs you "query failed" statement.
num rows check is also superfluous
most of the code you write is just repetitions
Like PHP users from the last century you are mixing database calls with HTML output. Now you see that the term "spaghetti code" was coined for a reason.
Your database related code rewritten with simple mysqli wrapper:
$rows = [];
$found = $db->getOne("SELECT id FROM stuff WHERE id = ?i", $id);
if ($found) {
$rows = $db->getAll("SELECT example FROM somewhere");
}
Now you can proceed to HTML output, either inline or (better) by including a template
?>
<?php if ($rows): ?>
<form method="post">
<?php foreach ($rows as $row): ?>
<?=$row['example']?>
<?php endforeach ?>
<input type="submit" value="Submit" />
</form>
<?php else: ?>
No records
<?php endif ?>

SQL query failing to INSERT new row into table

I have a chunk of PHP code that triggers if a button is pressed by the user. What I expect to happen is it checks to see if the user has the skill already assigned to them, and if not it performs an INSERT. Then if it does do nothing. And finally if the checkbox next to a skill is un-checked it checks to see if they have the skill already assigned and delete it if found.
The code is deleting the skills from the user no matter the condition of the checkboxes. Im sure I must be missing something but after starring at the code for hours I cannot see it.
Can anyone suggest a resolution?
PHP code:
if(isset($_POST['Update']))
{
$default = 0;
foreach($skills_array AS $skills_id=>$skills_name)
{
if (isset($_POST[$skills_name]))
{
if (empty($_POST[$skills_name.'exp']))
{
$exp = $default;
}
else
{
$exp = $_POST[$skills_name.'exp'];
}
$sql = $con->query("SELECT count(`UserID`) as total FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
if ($row = mysqli_fetch_assoc($sql))
{
$sql = $con->query("INSERT INTO `userskills` ( `UserID`, `SkillID`, `Experience`) VALUES ('$User', '$skills_id', '$exp')")
or die(mysqli_error($con));
//If the checkbox is not checked it will check to see if skill is already a skill assigned to the user. If they are it will delete it. If not it will ignore.
}
else
{
$sql = $con->query("UPDATE `userskills` SET `Experience` = '$exp' WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
}
}
else
{
$sql = $con->query("DELETE FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
}
}
header('Location: Account.php');
die();
}
else
{
echo 'Incorrect password please try again.';
}
}
HTML Code:
<div class="RightBody">
<form id="form2" name="form2" method="post" enctype="multipart/form-data">
<p><h3>Skills:</h3>
<?php
$result1 = $con->query("SELECT skills.`SkillID`, skills.`Description`, COUNT(userskills.`SkillID`) AS SkillUserHas, MAX(`Experience`) AS Experience
FROM `skills`
LEFT OUTER JOIN userskills
ON skills.`SkillID` = userskills.`SkillID` AND userskills.`UserID` = '$User'
GROUP BY skills.`SkillID`, skills.`Description`
ORDER BY FIELD(skills.`SkillID`, 1, 7, 9, 3, 4, 5, 6, 8)")
or die(mysqli_error($con));
while ($skillrow = $result1->fetch_assoc())
{
?>
<div class="CheckboxText">
<?php
echo '<label>';
echo '<input type="checkbox" name="'.$skillrow['Description'].'" id="CheckboxGroup1_'.$skillrow['SkillID'].'" class="skillselect" value="yes" '.(($skillrow['SkillUserHas'] > 0) ? 'checked' : '').'>';
echo $skillrow['Description'].'</label>';
echo '<input type="number" name="'.$skillrow['Description'].'exp" class="expnumber" placeholder="Enter Experience in years." value="'.$skillrow['Experience'].'">';
echo '<br />';
echo '<br />';
}
?>
</div>
</p>
</form>
</div>
Im not familiar with PHP, but yesterday I help in a similar problem
Here you create your query but your COUNT will always return a row, and if not skill the value is 0
$sql = $con->query("SELECT count(`UserID`) as total FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
So instead of if ($row = mysqli_fetch_assoc($sql)) you need something like
$row = mysqli_fetch_assoc($sql);
$skill = $row['total'];
if ($skill == 0 )
But that doesnt solve the error you describe, delete all skills or just the one selected?
Any way you have to check this IF that is the branch sending your skill to delete.
if (isset($_POST[$skills_name]))
This mean your $skills_name isnt defined. Maybe you should check for the value inside the array $skills_array?
My second guess check the code create on the webpage. Right click your page and selece see source code

PHP delete row via non PK

I have the user select a member ID, but I want it to delete the corresponding event ID (PK) so the row is just deleted. Can you suggest a simple and effective way of doing this? This is the code I am working on FYI.
Front end.
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Select member ID to <b> remove total and comment. </b>: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<input type="submit" value=">!DELETE!<" />
</form>
<?php
}
else
{
$mid = $_POST['meid'];
$db1 = new dbme();
$db1->openDB();
$numofrows = $db1->delete_total($meid);//basically kill off the entire row
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";
Back end method
function delete_total($mid, $meid) {
$sql = "DELETE FROM memberevent WHERE mid = $mid"; // This is the bit I am head scratching, might there be a way to use mid to identify the corresponding PK (meid) to delete so the entire row is killed?
$result = mysqli_query($this->conn, $sql);
if ($result) {
$numofrows = mysqli_affected_rows($this->conn);
return $numofrows;
}
else
$this->error_msg = "could not connect for some wierd reason";
return false ;
}
P.S I am aware it cannot work in its current form.
Here's the memberevent table structure.
meid (PK auto incr INT)
mid (int)
total (varchar)
comments (varchar)
ename (varchar)

how to insert an hidden field value along side with a checkbox in to the database

i am new here but i have a problem in inserting the id and the value of the checkboxes into my database here is the code of the form:
<?php
include('db.php');
$sql = "select * from sheet1 order by course_level asc";
$r = mysqli_query($dbc,$sql) or die(mysqli_error($dbc));
$co = '';
while($row = mysqli_fetch_array($r)) {
$co .= '<tr><td>'.$row['course_level'].'</td><td><input name="courses[]"
type= "checkbox" value = "'.$row['course_code'].'">'.$row['course_code'].'
</td> <td>'.$row['course_title'].'</td><td>'.$row['course_lecturer'].'
</td><input type=hidden name=cid[] value="'.$row['cid'].'">
</tr>';
}
?>
And this is the action code:
<?php
include('db.php');
if(isset($_POST['courses']))
echo 'lie';
else
echo 'true';
foreach($_POST['courses'] as $row=>$id){
$courses=$id;
$cid = $_POST['cid'][$row];
$sql = "insert into selected_courses values ('','$courses','$cid')";
$r = mysqli_query($dbc,$sql);
}
if($r)
echo 'done';
?>
thanks a lot.
You have several problems here, the main one being you are attempting to store two different reference values to the same row (course_code and cid) in your selected_courses table. You should really only store the primary key (cid?).
I'd suggest dropping the course_code column from your selected_courses table, remove the hidden input and structure your checkbox like this
<input type="checkbox"
name="courses[]"
value="<?php echo htmlspecialchars($row['cid']) ?>">
Then your INSERT query simply becomes
// Forget mysqli, move to PDO
$stmt = $dbc->prepare('INSERT INTO selected_courses (cid) VALUES (?)');
$stmt->bindParam(1, $cid);
foreach ($_POST['courses'] as $cid) {
$stmt->execute();
}

PHP: Determine whether its a checkbox is checked or not

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.

Categories