record inserts, but doesn't update mysql - php

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.

Related

Delete multiple MySQL rows when boxes are Unchecked on PHP Form

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!

PHP API returning wrong response for android app

I am creating a API for android developer in PHP in which he want to delete some values from database and want to show a message after that.
Now the problem is this data is deleting successfully but this API always shows else part message after complete the process. If I remove the else part its return the null which crash the android app. So I just want to give a proper json message to the android developer
Here is the code which I am trying
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1)
{
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_count as $table_count)
{
$user_count = mysql_query("select * from $table_count where user_name = '$user_name'");
$total_user_count = mysql_num_rows($user_count);
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
}
}
I know there is something wrong with this logic. But I need expert advise where my logic is wrong and what I have to do make it success
Problem with your original code, is that you are setting success/failure inside the loop. One of the four table may/may not contain the username. And if the last table don't have that, then as per your logic you are getting "record not found" even if previous iteration of the loop deleted data from the tables where username exists.
<?php
$conn = mysqli_connect(.....);
if($clear_my_property == "yes" && $clear_my_requirement == "yes" && $all_of_these == "yes" && $user_name_id == $user_name_id1) {
$tables_count = array("property_for_sale","property_for_rent","cpo_post_requirements");
$userHistoryDeleted = 0;
foreach($tables_count as $table_count) {
//if history is found, then it will be deleted otherwise not
mysql_query("delete from $table_count where user_name = '$user_name'");
if(mysqli_affected_rows($conn)) {
$userHistoryDeleted = 1;
}
}
$msg = 'Record Not Found!';
if($userHistoryDeleted) {
$msg = 'Clear Successfully All History!';
}
$response['success'] = $userHistoryDeleted;
$response['user']['error_msg'] = $msg;
}
Change your code :
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
if($user_sql)
{
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}
}
}
else
{
$response['success'] = 0;
$response['user']['error_msg'] = 'Record Not Found!';
}
to this one
if($total_user_count > 0)
{
$tables_data = array("property_for_sale","property_for_rent","cpo_post_requirements");
foreach($tables_data as $table_data)
{
$user_sql = mysql_query("delete from $table_data where user_name='$user_name'");
}
$response['success'] = 1;
$response['user']['error_msg'] = 'Clear Successfully All History!';
}

Only run php function once

I have this php function which checks a table in a database and checks to see if a user has a specific number in a field . This user could have a few rows where that filed has that number .
The problem with this is that it will run the if statement multiple times, triggering the resulting function to run multiple times. How can I stop this and just have the function say "okay found a match for al1 and running function , moving onto al2"
function countNewBadges() {
require "connect.php";
$count = mysqli_query($connection,"SELECT users.studentid, al1, al2, al3 FROM userbadges ub INNER JOIN users ON users.id = ub.user_id WHERE studentid = '".$_SESSION["studentid"]."'") or die(mysqli_error($connection));
while ($data = mysqli_fetch_array($count)) {
if ($data['al1'] == 1)
{
unlockedBadges();
}
else if ($data['al2'] == 1)
{
echo "No New Badges";
}
else if ($data['al3'] == 1)
{
echo "No New Badges";
}
}
}
How can I have the function say "okay found a match for al1 and running function, moving onto al2"
Just use a flag variable:
$flag = false;
while ($data = mysqli_fetch_array($count)) {
if ($data['al1'] == 1 && $flag === false)
{
unlockedBadges();
$flag = true;
}
else if ($data['al2'] == 1)
{
echo "No New Badges";
}
else if ($data['al3'] == 1)
{
echo "No New Badges";
}
}
While user4035's answer will stop multiple data entries to truly only run a function once you need to search and then act after (using as was said) a flag.
function countNewBadges() {
require "connect.php";
$count = mysqli_query($connection,"SELECT users.studentid, al1, al2, al3 FROM userbadges ub INNER JOIN users ON users.id = ub.user_id WHERE studentid = '".$_SESSION["studentid"]."'") or die(mysqli_error($connection));
$foundit=false;
while ($data = mysqli_fetch_array($count)) {
if ($data['al1'] == 1)
{
$foundit=true;
}
else if ($data['al2'] == 1)
{
echo "No New Badges";
}
else if ($data['al3'] == 1)
{
echo "No New Badges";
}
}
if($foundit){
unlockedBadges();
}
}

How to get and compare row values in PHP/MySQL?

I would like to know what code I would need to use to get the values from a row (which would naturally have data from different columns)
I would like to check if the IP address is the same as the Poll ID. As you would expect the IP address is stored in one column, and the poll id in a next column.
$q = mysql_query("SELECT * FROM logs");
while($row = mysql_fetch_array($q))
{
if(($ip = $_SERVER['REMOTE_ADDR']) == $row['ip'])
{
$duplicateIP = true;
}//end if
if(($row['poll_id'] == 1))
{
$duplicatePoll = true;
}//end if
}//end while
I realised this code won't work as it will return the poll id to be true as long as it is equal to 1. How do I ensure that it will only return to be true if that poll id matches the IP address? Thanks.
Instead of:
if(($ip = $_SERVER['REMOTE_ADDR']) == $row['ip'])
{
$duplicateIP = true;
}//end if
if(($row['poll_id'] == 1))
{
$duplicatePoll = true;
}//end if
You should write:
if($_SERVER['REMOTE_ADDR'] == $row['ip'] && $row['poll_id'] == 1){
$duplicateIP = true;
}//end if
Or change your query:
$q = mysql_query(
"SELECT * FROM logs WHERE ip = '".$_SERVER['REMOTE_ADDR'] .
"' and poll_id = '".$iPollid."' "
);

Insert on duplicate key update returns value of 0

I am creating a web page where you can edit local listing sites for clients. I am using the INSERT ... ON DUPLICATE KEY UPDATE syntax in mysql and php. Below is the code:
edit-listings-exec.php
<?
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
$member_id = $_SESSION['MEMBER_ID'];
$userresult = mysqli_query($link, "SELECT username
FROM members
WHERE member_id = '$member_id'");
$row = mysqli_fetch_array($userresult);
$username = $row['username'];
//run a for loop to check for duplicates
for ($i=1; $i < 10; $i++) {
$selectbox = $_POST['listing'.$i];
for ($j=1; $j < 10; $j++) {
if ($j != $i) {
if ($_POST['listing'.$j] === $selectbox && $_POST['listing'.$j] != "") {
$errmsg_arr[] = "Duplicate listing source '$selectbox'";
$errflag = true;
break;
}
}
}
}
//if there are input validations redirect back to main page
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: edit-listings.php");
exit();
}
//run loop to define post variables
for ($k=1; $k < 10; $k++) {
${'listing'.$k} = mysqli_real_escape_string($link, $_POST['listing'.$k]);
${'listing'.$k.'_site'} = mysqli_real_escape_string($link, $_POST['listing'.$k.'_site']);
}
//insert listings into local_listings table for the user
$qry = "INSERT INTO local_listings (
member_id,
username,
listing1,
listing1_site,
listing2,
listing2_site,
listing3,
listing3_site,
listing4,
listing4_site,
listing5,
listing5_site,
listing6,
listing6_site,
listing7,
listing7_site,
listing8,
listing8_site,
listing9,
listing9_site)
VALUES (
'$member_id',
'$username',
'$listing1',
'$listing1_site',
'$listing2',
'$listing2_site',
'$listing3',
'$listing3_site',
'$listing4',
'$listing4_site',
'$listing5',
'$listing5_site',
'$listing6',
'$listing6_site',
'$listing7',
'$listing7_site',
'$listing8',
'$listing8_site',
'$listing9',
'$listing9_site')
ON DUPLICATE KEY UPDATE
listing1 = '$listing1',
listing1_site = '$listing1_site',
listing2 = '$listing2',
listing2_site = '$listing2_site',
listing3 = '$listing3',
listing3_site = '$listing3_site',
listing4 = '$listing4',
listing4_site = '$listing4_site',
listing5 = '$listing5',
listing5_site = '$listing5_site',
listing6 = '$listing6',
listing6_site = '$listing6_site',
listing7 = '$listing7',
listing7_site = '$listing7_site',
listing8 = '$listing8',
listing8_site = '$listing8_site',
listing9 = '$listing9',
listing9_site = '$listing9_site'";
$result = mysqli_query($link, $qry);
if (mysqli_affected_rows($result) < 1) {
$errmsg_arr[] = "Unable to insert listings for $username";
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
header ("location: edit-listings.php");
}
elseif (mysqli_affected_rows($result) === 1) {
$_SESSION['RESULT'] = "New listings for '$username' inserted successfully";
header ("location: edit-listings-success.php");
}
elseif (mysqli_affected_rows($result) === 2) {
$_SESSION['RESULT'] = "Listings for '$username' have been updated";
header ("location: edit-listings-success.php");
}
?>
The data is successfully inserting into the local_listings table but mysqli_affected_rows always returns a value of 0. It should be returning a value of 1 if it inserts a new row or 2 if it simply updates. Any ideas why this is happening?
Try this:
if (mysqli_affected_rows($link) < 1) {
... your code
}
take a look here

Categories