0

Trying to update a column ($_POST['dtf']) value to null based on another columns value ($_POST['pid']), but its not working. I have tried different versions of the MySQL statement but with no avail.
AJAX

      $(function() {
      $(".remove-tf").click(function() {
      $.ajax({
          type: 'POST',
          url: 'tf-delete.php',
          data: 'pid=' + $(".pid").attr("value") + '&dtf=' + $(this).val()
      });
      });
      });

PHP

<?php
include 'sqlconnection.php';
$conn = OpenCon();
$sql = "UPDATE tasks SET '".$_POST['dtf']."'=NULL WHERE pid=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_POST['pid']);
if ($stmt->execute()){
    header('Location: listings.php');
};
$stmt->close();
CloseCon($conn);
?>

HTML

<input type="hidden" class="pid" name="pid" value="">
<button class="remove-tf" name="submit" type="button" value="taskimg0">Remove</button>

1 Answers1

1

This is your code:

$sql = "UPDATE tasks SET '".$_POST['dtf']."' = NULL WHERE pid = ?";

This produce a query like:

UPDATE tasks set 'foo' = null where pid = ?

This is not valid MySQL. The column name should not be be surrounded with single quotes (in ANSI SQL, single quotes are there for strings litterals).

Just change your code to:

$sql = "UPDATE tasks SET ".$_POST['dtf']." = NULL WHERE pid = ?";

Or if you want to use quoted identifiers, use backticks:

$sql = "UPDATE tasks SET `".$_POST['dtf']."` = NULL WHERE pid = ?";
Barmar
  • 741,623
  • 53
  • 500
  • 612
GMB
  • 216,147
  • 25
  • 84
  • 135