-1

Hello srry for bad english, i'm trying to insert some formdata to my sql database with fetch request, the row was added and the id counts +1, but theres no extra data added to the columns "nomtar","destar",etc

JS function on submit form:

function enviarDatos(e){
    e.preventDefault();
    var nomtar = document.getElementById('nomtar').value;
    var destar = document.getElementById('destar').value;
    var usu2tar = document.getElementById('usu2tar').value;
    var fectar = document.getElementById('fectar').value;
    formData = new FormData();
    formData.append('nomtar',nomtar);
    formData.append('destar',destar);
    formData.append('usu2tar',usu2tar);
    formData.append('fectar',fectar);
    fetch('servicios/agregar.php',{
      method: 'POST',
      headers: {
                  'Content-Type': 'application/json'
              },
      body: JSON.stringify(formData)
    }).then(response => {
      if(response.ok){
        console.log("datos enviados");
      }
      else{
        console.log("datos no enviados");
      }
    }).catch((error) => {
      console.log(error)
      });
  }

agregar.php FILE:

    <?php
  session_start();
  include('conexion.php');
  $data = json_decode(file_get_contents('php://input'), true);

  $nomtar=$data['nomtar'];
  $destar=$data['destar'];
  $fectar=date('Y-m-d',strtotime($data['fectar']));
  $usu1tar=$_SESSION['idusu'];
  $usu2tar=$data['usu2tar'];
  $query="select idusu from usuario where nombre='$usu2tar'";
  $result1=mysqli_query($con,$query);
  if($result1){
    while($row=mysqli_fetch_array($result1)){

        $idusu=$row['idusu'];

    }
  }


  $sql="INSERT INTO tarea(usu1tar,usu2tar,nomtar,destar,fectar,esttar) VALUES('$usu1tar','$idusu','$nomtar','$destar','$fectar',1)";
  $result2=mysqli_query($con,$sql) or die(mysqli_error($con));


  mysqli_close($con);
?>
Shakur
  • 3
  • 1
  • What debugging have you done? What values do the variables have? Regardless, this is not how to write database code. Please look up **prepared statements,** you will make your code more secure and quite possibly fix your problem. – miken32 Apr 27 '21 at 22:18
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Apr 27 '21 at 22:39
  • It is a very bad idea to use `die(mysqli_error($conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Apr 27 '21 at 22:40

1 Answers1

0

There's no need to convert your form data to JSON. Fetch understands FormData directly.

Change this line

body: JSON.stringify(formData)

to this:

  body: formData

Now your PHP code can extract the incoming data from $_POST without having to read php://input

    <?php
  session_start();
  include('conexion.php');
  // remove line that reads php://input here.

  $nomtar=$_POST['nomtar'];
  $destar=$_POST['destar'];
  $fectar=date('Y-m-d',strtotime($_POST['fectar']));
  $usu1tar=$_SESSION['idusu'];
  $usu2tar=$_POST['usu2tar'];
// rest of code follows

That should get you going, but be aware, your code is vulnerable to SQL injection. Once you get this fixed you should refactor your code to use prepared statements.

Note: FormData can extract data directly from a form without you extracting it field by field. let formData = new FormData(document.getElementById('formId')) will do it in one operation.