0

I have a form with 3 data, name, data1, data2 but data1 and data2 is a dynamic array where I can add various data with the + button to this array, but I have not been able to save them in the database which are php and MySQL , I have tried to make my code work but I have not succeeded, and what I need is for me to save the array in the database, I have tried to do it but my code does not work. I send my source code:

https://codesandbox.io/s/peaceful-http-bg949?file=/src/App.js

import React, {useState} from 'react';
import axios from 'axios';

import {
  Grid,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper
} from "@material-ui/core";
import AddCircleOutlineIcon from "@material-ui/icons/AddCircleOutline";
import { withStyles, makeStyles } from "@material-ui/core/styles";
import DeleteIcon from "@material-ui/icons/Delete";

const StyledTableRow = withStyles((theme) => ({
  root: {
    "&:nth-of-type(odd)": {
      backgroundColor: theme.palette.action.hover
    }
  }
}))(TableRow);

const useStyles = makeStyles((theme) => ({
  paper: {
    display: "flex",
    flexDirection: "column",
    padding: "30px 40px",
    marginTop: "50px",
    marginLeft: "20px",
    marginRight: "20px"
  },

  heading: {
    paddingLeft: "10px"
  },

  label: {
    lineHeight: "2",
    fontSize: "14px"
  },
  input: {
    height: "10px"
  },
  table: {
    minWidth: 700
  }
}));

const options = [
  { value: 1, label: 1 },
  { value: 2, label: 2 },
  { value: 3, label: 3 }
];

function Pruebas() {
    const baseUrlAd = 'https://www.inventarios.gemcont.com/apiGemcont/compras/ingresos/'; 
    const [data, setData]=useState([]);
    const [frameworkSeleccionado, setFrameworkSeleccionado]=useState({
        id_ingreso:'',
        nombre:'',
        dato1:'',
        dato2:''
      });

    const handleChange=e=>{
        const {name, value}=e.target;
        setFrameworkSeleccionado((prevState)=>({
          ...prevState,
          [name]: value
        }))
       console.log(frameworkSeleccionado);
      }

      const peticionPost = async() =>{
        var f = new FormData();
        f.append("nombre", frameworkSeleccionado.nombre);
        f.append("dato1", frameworkSeleccionado.dato1);
        f.append("dato2", frameworkSeleccionado.dato2);
        f.append("METHOD", "POST_prueba");
        await axios.post(baseUrlAd,f)
        .then(response=>{
         setData(data.concat(response.data));
        }).catch(error=>{
          console.log(error);
        })
    
      }

  const classes = useStyles();

  const [roomInputs, setRoomInputs] = useState([
    { dato1: "", dato2: "" }
  ]);

  const handleRoomChange = (option, index, name) => {
    const value = option.value;
    console.log(value);
    const list = [...roomInputs];
    list[index][name] = value;
    setRoomInputs(list);
  };

  const handleRemoveClickRoom = (index) => {
    const list = [...roomInputs];
    list.splice(index, 1);
    setRoomInputs(list);
  };

  const handleAddClickRoom = () => {
    setRoomInputs([...roomInputs, { dato1: "", dato2: "" }]);
  };

  
 
    return (
<div className="content-wrapper">
    
    <div className="content-header">
      <div className="container-fluid">
        
          <div className="col-sm-12">

          <div class="card">
              <div class="card-header">
              <h3 class="card-title">Datos</h3>
              </div>
            
              <div class="card-body">
                
                  <div class="row">  

                  <div class="col-sm-4">
                  <div class="input-group">
                  <input type="text" name="nombre"
                  placeholder='nombre' className="form-control"/>
                  </div>
                  </div>


                  </div>

                  <div class="row">
                  <div class="col-sm-12">
                  
                  
        <br />
          <Grid item sm={12}>
            <TableContainer component={Paper} variant="outlined">
              <Table className={classes.table} aria-label="customized table">
                <TableHead>
                  <TableRow>
                    <TableCell>#</TableCell>
                    <TableCell align="left">dato1</TableCell>
                    <TableCell align="left">dato2</TableCell>
                  </TableRow>
                  
                </TableHead>
                <TableBody>
                  {roomInputs.map((x, i) => (
                    <StyledTableRow key={i}>
                      <TableCell component="th" scope="row">
                        {i + 1}
                      </TableCell>
                      <TableCell align="left">
                        <input 
                        type="text"
                        className="form-control"
                        name="dato1"
                        value={options.value}
                        onChange={option => handleRoomChange(option, i, "dato1")}
                        />
                      </TableCell>
                      <TableCell align="left">
                      <input 
                        type="number"
                        name="dato2"
                        className="form-control"
                        value={options.value}
                        onChange={option => handleRoomChange(option, i, "dato2")}
                        />
                      </TableCell>

            

                      <TableCell align="left">
                        {roomInputs.length !== 1 && (
                          <DeleteIcon
                            onClick={() => handleRemoveClickRoom(i)}
                            style={{
                              marginRight: "10px",
                              marginTop: "4px",
                              cursor: "pointer"
                            }}
                          />
                        )}
                        {roomInputs.length - 1 === i && (
                          <AddCircleOutlineIcon
                            onClick={handleAddClickRoom}
                            style={{ marginTop: "4px", cursor: "pointer" }}
                          />
                        )}
                      </TableCell>
                    </StyledTableRow>
                  ))}
                </TableBody>
               
                  
              </Table>
            </TableContainer>
          </Grid>
         
      
     
             </div>
                  </div>
                  <br />
                  <button className="btn btn-primary" onClick={()=>peticionPost()}> Registrar</button>
               
              </div>
             
            </div>     

      </div>

      </div>
      </div>
    
  </div>
    )
}



export default Pruebas

PHP

<?php

include '../../bd/global.php';

header('Access-Control-Allow-Origin: *');

if($_POST['METHOD']=='POST_prueba'){
    unset($_POST['METHOD']);
    $nombre=$_POST['nombre'];
    $query="insert into ingresos(nombre) values ('$nombre')";
    $queryAutoIncrement="select MAX(id_ingreso) as id_ingreso from ingresos";
    $resultado=metodoPost($query, $queryAutoIncrement);
    echo json_encode($resultado);
        $num_elementos=0;
        $sw=true;
        while ($num_elementos < count($idarticulo))
        {
            $sql_detalle = "INSERT INTO detalle_ingresos(id_ingreso, dato1, dato2) VALUES ('$idingresonew', '$idarticulo[$num_elementos]','$dato1[$num_elementos]','$dato2[$num_elementos]')";
            ejecutarConsulta($sql_detalle) or $sw = false;
            $num_elementos=$num_elementos + 1;
        }
        
    return $sw;
        
    header("HTTP/1.1 200 OK");
    exit();
}

header("HTTP/1.1 400 Bad Request");


?>

Data base enter image description here

Giovanny
  • 131
  • 12

1 Answers1

0

Sorry i am not answering you question but i've noticed a vulnerable code in your SQL query which can allow an attacker to inject in your future website, therefore i advice you to make a look here ; How can I prevent SQL injection in PHP?

Seif-Ch
  • 44
  • 1
  • 5