0

i have been stuck on this for a little while now i am updating a SQL table through a form in HTML, via PHP and i have the request working when i manually enter the values however when i use $_POST it doesnt work and comes up with a syntax error. i am fairly new to SQL and really appreciate any help given.


//$sql = "UPDATE personnel SET firstName='Lawo', lastName='Fish', email='someThing@aol.col', jobTitle='' WHERE id=4";

$sql = "UPDATE personnel SET firstName=" . $_POST['fname'] . ", lastName=" . $_POST['lname'] . ", email=" . $_POST['email'] . ", jobTitle= " . $_POST['job'] . " WHERE id=" . $_REQUEST['personID'];

if ($conn->query($sql) === TRUE) {
  echo "Record updated successfully";
} else {
  echo "Error updating record: " . $conn->error;
}

$conn->close();```

this is my AJAX in script:

    ```updateFunc.addEventListener('click', function(e) {
      fName = document.getElementById('txtFirstName').value; 
      lName = document.getElementById('txtLastName').value;
      email = document.getElementById('txtEmail').value;
      job = document.getElementById('txtJobTitle').value;
    
      console.log(job);
    
      $.ajax({
        url: "PHP/update.php",
        type: 'POST',
        dataType: 'json',
        data: {
          personID: personID,
          fname: fName,
          lname: lName,
          email: email,
          job: job,
        },```
  • The/all single quotes `'` from your original statement are missing in your concatenated string. BTW: Please read about [SQL Injection](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Ocaso Protal Oct 29 '20 at 12:49
  • i am unsure how you mean to write the concatenated string: $sql = "UPDATE personnel SET firstName=" . $_POST['fname'] . ", the single quote is around 'fname'? – Liam Scott Oct 29 '20 at 12:57
  • 1
    `$sql = "UPDATE personnel SET firstName='" . $_POST['fname'] . "', lastName='" . $_` and so on. "Add single quotes around your $_POST stuff". Or better yet: Don't do this! Read the link about SQL Injection in my first comment. – Ocaso Protal Oct 29 '20 at 13:00
  • how would you recommend writing it if not in this way? Thanks for your help – Liam Scott Oct 29 '20 at 13:08
  • [Use prepared statements and parameterized queries](https://stackoverflow.com/a/60496/307138) – Ocaso Protal Oct 29 '20 at 13:20

0 Answers0