Delete multiple MySQL rows when boxes are Unchecked on PHP Form - php

My current code seems to delete every row in the table.
Need to delete only the ones that are unchecked.
here is my code:
$assigned_array = array($_POST['employee_assigned']);
$assigned_employees = implode (",", $assigned_array);
// update unchecked assignments
// get all employees and delete the ones not in the checked list
$get_emp_sql = "SELECT * FROM `accounts` WHERE `permissions` > 0";
$get_emp_result = mysqli_query($dblink, $get_emp_sql);
while ($get_emp_row = mysqli_fetch_array($get_emp_result)) {
// delete rows that are not checked
$delete_assignment = "DELETE FROM `provider_assignments` WHERE `provider_id`='".$pro_id."' AND '".$get_emp_row['id']."' NOT IN ('".$assigned_employees."')";
if (mysqli_query($dblink, $delete_assignment)) {
} else {
die ("Unassignment error.");
}
}
This currently deletes every row, including the boxes that are checked (which are then added, but then deleted by the issue).
Need to add the checked, and remove any unchecked if they exist.

Created an array of all checked employees ID's.
if (strlen($_POST['employee_assigned']) > 0) {
$assigned_employees = implode (",", $_POST['employee_assigned']);
}
// update unchecked assignments
// get all employees and delete the ones not in the clicked list
$get_emp_sql = "SELECT * FROM `accounts` WHERE `permissions` > 0";
$get_emp_result = mysqli_query($dblink, $get_emp_sql);
while ($get_emp_row = mysqli_fetch_array($get_emp_result)) {
if (strlen($assigned_employees == 0)) {
// delete all rows for this provider
$delete_assignment = "DELETE FROM `provider_assignments` WHERE `provider_id`='".$pro_id."'";
} else {
// delete rows that are not checked
$delete_assignment = "DELETE FROM `provider_assignments` WHERE `provider_id`='".$pro_id."' AND '".$get_emp_row['id']."' NOT IN ('".$assigned_employees."')";
}
if (mysqli_query($dblink, $delete_assignment)) {
} else {
die ("Unassignment error.");
}
}
// update checked assignments
if (strlen($_POST['employee_assigned']) > 0) {
foreach ($_POST['employee_assigned'] as $assign_this_employee) {
// check for existing assignment
$check_exist = "SELECT * FROM `provider_assignments` WHERE `provider_id` = '".$pro_id."' AND `employee_id` = '".$assign_this_employee."'";
$exist_result = mysqli_query($dblink, $check_exist);
$exist_count = mysqli_num_rows ($exist_result);
// if assignment doesn't exist, insert assignment
if ($exist_count == 0) {
// insert sql
$add_assignment_sql = "INSERT INTO `provider_assignments` (`provider_id`, `employee_id`) VALUES ('".$pro_id."', '".$assign_this_employee."')";
// execute sql
if (mysqli_query($dblink, $add_assignment_sql)) {
} else {
die ("assignment error");
}
}
}
}
This code works great.. Any comments are welcome!

Related

record inserts, but doesn't update mysql

I'm having an issue trying to update my database. I'm able to insert if it doesn't exist, but it doesn't update the record if exists. I think is not finding the current values of the table. Any ideas?
<?php
function add_log($input_output, $l_sales, $l_enroll, $l_offers)
{
global $database;
$date = date('m-d-Y');
$l_sales = safety_filter($l_sales);
$l_enroll = safety_filter($l_enroll);
$l_offers = safety_filter($l_offers);
$cusersup = get_the_current_user('u_manager');
$cuseropm = get_the_current_user('u_opsmanager');
$cuserid = get_the_current_user('id');
$cuser = get_the_current_user('user_name');
if($input_output == 'input')
{
$query_call = mysql_query("SELECT 1 FROM $database->log WHERE l_date='$date' AND l_user_name='$cuser'");
if(mysql_num_rows($query_call) > 0)
{
while($list_calls = mysql_fetch_assoc($query_call))
{
$old_calls = $list_calls['l_calls'];
$old_sales = $list_calls['l_sales'];
$old_enroll = $list_calls['l_enroll'];
$old_offers = $list_calls['l_offers'];
}
$update = mysql_query("UPDATE $database->log SET
l_call=[$old_calls] + [1],
l_sales=[$old_sales] + [$l_sales],
l_enroll=[$old_enroll] + [$l_enroll],
l_offers=[$old_offers] + [$l_offers]
WHERE l_date='$date' AND l
_user_name='$cuser'");
if(mysql_affected_rows() > 0){return true; }
else { if($update == true){ return true; } else { return false; } }
}
else
{
mysql_query("INSERT INTO $database->log (l_date, l_user_name, l_calls, l_sales, l_enroll, l_offers) VALUES ('$date', '$cuser', '1', '$l_sales', '$l_enroll', '$l_offers')");
if(mysql_affected_rows() > 0){return true; }
else{ return false; }
}
}
}
?>
I think the problem is that you are selecting 1 ("SELECT 1 FROM..."), so you are never getting any of the values from the table (just the number "1"). This tells you something is there, but doesn't actually return any values.
Try selecting all fields ("SELECT * FROM..."), or at least list the fields you need to do the update.

On refresh, values keep adding in drop down

Code:
public function getEmployeeId() {
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
// Cannot Access this page without Login.
}
$_SESSION['ids'][] = "";
$query = mysqli_query($this->connection, "SELECT EmployeeId from employees where EmployeeId NOT IN(Select EmployeeId from employeeprofile)") or die("Query execution failed: " . mysqli_error());
while ($row = $query->fetch_assoc()) {
// Push the id to the array.
$_SESSION['ids'][] = $row["EmployeeId"];
}
}
Values are coming from database and whenever I refresh duplicate values are added. I don't know what to do.
That's because every time you refresh the page, (probably with every getEmployeeId() method call) SQL query gets executed and employee ids gets appended to $_SESSION['ids'] array. You need to encapsulate that block of code inside an if block.
public function getEmployeeId() {
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
exit();
}
if(!isset($_SESSION['ids']) && count($_SESSION['ids']) == 0){
$_SESSION['ids'][] = "";
$query = mysqli_query($this->connection, "SELECT EmployeeId from employees where EmployeeId NOT IN(Select EmployeeId from employeeprofile)") or die("Query execution failed: " . mysqli_error());
while ($row = $query->fetch_assoc()) {
$_SESSION['ids'][] = $row["EmployeeId"];
}
}
}
Sidenote: You need to add exit(); after header(...); statement, because header(...); alone itself is not sufficient to redirect the user to a different page.

PHP Validating Submit

I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query

How do I check if a field in my mySQL database is empty in PHP

I would like to know how to how to check if a field (column) is empty for a specific user.
I have connected successfully to a mySQL database, I have entered a user and I have fields that are empty. I have a post form that allows users to enter information. Based on whether other fields are empty, I would like them to fill accordingly. I would like to use logic to determine whether a field is empty or not. I am using the following:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(trim($_POST['listing_link']) == '') {
}
else if(empty($listing_link1)) {
$listing_link1 = $_POST['listing_link'];
$listing_link1 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link1`='$listing_link1'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link1) && empty($listing_link2)) {
$listing_link2 = $_POST['listing_link'];
$listing_link2 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link2`='$listing_link2'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link2) && empty($listing_link3)) {
$listing_link3 = $_POST['listing_link'];
$listing_link3 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link3`='$listing_link3'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link3) && empty($listing_link4)) {
$listing_link4 = $_POST['listing_link'];
$listing_link4 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link4`='$listing_link4'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link4) && empty($listing_link5)) {
$listing_link5 = $_POST['listing_link'];
$listing_link5 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link5`='$listing_link5'
WHERE `email`='$emailstring'";
}
$result = mysql_query($query);
}
?>
This code checks whether there is anything entered by the user when they hit the button for the "listing_link". If not, then nothing happens. If something is entered, then it will check to determine if any of the other fields are filled (listing_link1, listing_link2...listing_link5). The $listing_link1 - 5 variables are supposed to take on the information.
I cannot get the other else ifs to run except for:
else if(empty($listing_link1)) {
$listing_link1 = $_POST['listing_link'];
$listing_link1 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link1`='$listing_link1'
WHERE `email`='$emailstring'";
And continually running the code by hitting the button for the form just replaces the listing_link1 variable with the newly entered information.
Perhaps there is something wrong with the logic written here. Please help if you can.
You're not defining $listing_link1 until after you've checked to see if it's empty:
else if(empty($listing_link1))
{
$listing_link1 = $_POST['listing_link'];
Flip 'em around:
$listing_link1 = $_POST['listing_link'];
if(empty($listing_link1))
{
If I got you right, this would solve your woes:
$empty = 0;
for($i=1; $i<=5; $i++){
$varname = "listinglink$i";
if(empty($$varname)){
$empty = $i;
break;
}
}
if($empty > 0){
$update_field = "listinglink{$empty}";
$update_data = $_POST['listing_link'];
mysql_query("UPDATE users SET `$update_field`='$update_data'
WHERE email='$emailstring'");
}
What I do there is spin a loop to check which one is the first empty *listing_link* and as soon as I find it, set some variable to its number and quit the loop. From there it's pretty much simple.
What this does: $$varname = 1; is that it takes the value of $varname and tries to use it as a variable name, for example:
$test = "groovy.";
$varname = "test";
echo $$varname; // eqivalent to "echo $test"
Fun technique :)

php mysql check previous row

I have output from a select query as below
id price valid
1000368 69.95 1
1000369 69.94 0
1000370 69.95 0
now in php I am trying to pass the id 1000369 in function. the funciton can execute only if the valid =1 for id 1000368. if it's not 1 then it will throw error. so if the id passed is 1000370, it will check if valid =1 for 1000369.
how can i check this? I think it is logically possible to do but I am not able to code it i tried using foreach but at the end it always checks the last record 1000370 and so it throws error.
regards
Use a boolean variable:
<?php
$lastValid=false;
while($row = mysql_fetch_array($result))
{
if ($lastValid) {
myFunction();
}
$lastValid = $row['valid'];
}
?>
(Excuse possible errors, have no access to a console at the moment.)
If I understand correctly you want to check the if the previous id is valid.
$prev['valid'] = 0;
foreach($input as $i){
if($prev['valid']){
// Execute function
}
$prev = $i;
}
<?php
$sql = "SELECT * FROM tablename";
$qry = mysql_query($sql);
while($row = mysql_fetch_array($qry))
{
if ($row['valid'] == 1)
{
// do some actions
}
}
?>
I really really recommend walking through some tutorials. This is basic stuff man.
Here is how to request a specific record:
//This is to inspect a specific record
$id = '1000369'; //**some specified value**
$sql = "SELECT * FROM data_tbl WHERE id = $id";
$data = mysql_fetch_assoc(mysql_query($sql));
$valid = $data['valid'];
if ($valid == 1)
//Do this
else
//Do that
And here is how to loop through all the records and check each.
//This is to loop through all of it.
$sql = "SELECT * FROM data_tbl";
$res = mysql_query($sql);
$previous_row = null;
while ($row = mysql_fetch_assoc($res))
{
some_action($row, $previous_row);
$previous_row = $row; //At the end of the call the current row becomes the previous one. This way you can refer to it in the next iteration through the loop
}
function some_action($data, $previous_data)
{
if (!empty($previous_data) && $condition_is_met)
{
//Use previous data
$valid = $previous_data['valid'];
}
else
{
//Use data
$valid = $data['valid'];
}
if ($valid == 1)
{
//Do the valid thing
}
else
{
//Do the not valid thing
}
//Do whatever
}
Here are some links to some good tutorials:
http://www.phpfreaks.com/tutorials
http://php.net/manual/en/tutorial.php

Categories