I have a form in reactjs which has a normal variable called "name" and two arrays, one called "data1" and the other "data2", but when saving from reactjs it is only saving the variable "name" in base of data.
I need that they also save the arrangements in the database but I have not achieved it.
the mysql database only has one table called revenue2 and 4 fields: revenue_id, name, data1, data2
https://codesandbox.io/s/ecstatic-browser-nvcee?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 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 [roomInputs, setRoomInputs] = useState([
{ dato1: "", dato2: "" }
]);
const handleRoomChange = (value, index, name) => {
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" onChange={handleChange}/>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<br />
<Grid item sm={12}>
<TableContainer component={Paper} variant="outlined">
<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")}
onChange={event => handleRoomChange(event.target.value, i, "dato1")}
/>
</TableCell>
<TableCell align="left">
<input
type="number"
name="dato2"
className="form-control"
value={options.value}
//onChange={option => handleRoomChange(option, i, "dato2")}
onChange={event => handleRoomChange(event.target.value, 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'];
$dato1=$_POST['dato1'];
$dato2=$_POST['dato2'];
$query="insert into ingresos2(nombre,dato1,dato2) values ('$nombre','$dato1','$dato2')";
$queryAutoIncrement="select MAX(id_ingreso) as id_ingreso from ingresos2";
$resultado=metodoPost($query, $queryAutoIncrement);
echo json_encode($resultado);
header("HTTP/1.1 200 OK");
exit();
}
header("HTTP/1.1 400 Bad Request");
?>
The code you've created to send the data to PHP doesn't get the data from where you're storing it.
dato1
Remember that you are storing the and valuesdato2
in one element per table row, so you will need to access the first element of the two-dimensional arrayroomInputs
to access thedato1
and propertiesdato2
.Since you want to send multiple values to PHP there are different ways to do it:
FormData f
) all the values by means of incremental arrays (for example,f.append("dato1[]", ...)
) and having PHP iterate through each of them.We are going to focus on this last method since, in my opinion, it is the best way to do it.
Sending the data from Javascript to PHP:
As you can see the code has been greatly simplified. Two properties are going to be sent, with names
frameworkSeleccionado
androomInputs
that will contain the content of the named objects.Now let's go to the server side, where the data is received. There the most important thing is the way in which PHP receives data from Javascript:
When sending data in the POST body that is not encoded as form data (
multipart/form-data
), you must receive the data through standard input (php://input
) and then convert it to native PHP data usingjson_decode()
.Once the data is obtained, we can work with it in the usual way.
Your code could look like this (schematically, I don't know the details of your implementation):
In the loop
foreach
you have the possibility to add an element to the table for each row of the table.The first edition can be consulted here .