使用php和reactj将数组保存在mysql中
我在reactjs中有一个表单,它保存一个变量“name”和两个动态数组,一个称为“data1”和“data2”,每个数组可以包含多个值,因为我可以从reactjs添加更多动态值到那里,但不是我已经能够从 php 传递保存在 mysql 中的数组值,因为它只保存 data1 和 data2 数组的名称和前两个数据:
https://codesandbox.io/s/ecstatic -browser-nvcee?file=/src/App.js:0-8794
我需要能够将完整的数组“data1”和data2保存在数据库。
reactjs
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/index2.php';
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 peticionPost = async () => {
var f = new FormData();
f.append("nombre", frameworkSeleccionado.nombre);
/* Los datos están en la matriz bidimensional "roomInputs" */
/* f.append("dato1", roomInputs[0].dato1);
f.append("dato2", roomInputs[0].dato2);*/
f.append("data", JSON.stringify(roomInputs));
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 handleRoomChange = (value, index, name) => {
const list = [...roomInputs ];
list[index][name] = value;
setRoomInputs(list);
};*/
/*const handleRoomChange = (value, index, name) => {
setFrameworkSeleccionado((prevState) => ({
...prevState,
[name]: value
}));
};*/
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: *');
//tried 1
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();
}
//tried 2
if($_POST['METHOD']=='POST_prueba'){
unset($_POST['METHOD']);
$nombre=$_POST['nombre'];
$data=json_decode($_POST['data']);
foreach ($data as $row) {
$dato1=$row['dato1'];
$dato2=$row['dato2'];
//aqui debes hacer cada inserción en base de datos
}
$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();
}
//tried 3
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($id_detalle))
{
$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");
?>
I have a form in reactjs that saves a variable "name" and two dynamic arrays, one is called "data1" and "data2", each array can contain several values since I can add more dynamic values from reactjs to there, but not I have been able to pass those values of the array that are saved in mysql from the php since it only saves the name and the first two data of the array of data1 and data2:
https://codesandbox.io/s/ecstatic-browser-nvcee?file=/src/App.js:0-8794
I need to be able to save the complete arrays "data1" and data2 in the database.
reactjs
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/index2.php';
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 peticionPost = async () => {
var f = new FormData();
f.append("nombre", frameworkSeleccionado.nombre);
/* Los datos están en la matriz bidimensional "roomInputs" */
/* f.append("dato1", roomInputs[0].dato1);
f.append("dato2", roomInputs[0].dato2);*/
f.append("data", JSON.stringify(roomInputs));
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 handleRoomChange = (value, index, name) => {
const list = [...roomInputs ];
list[index][name] = value;
setRoomInputs(list);
};*/
/*const handleRoomChange = (value, index, name) => {
setFrameworkSeleccionado((prevState) => ({
...prevState,
[name]: value
}));
};*/
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 - failed attempts
<?php
include '../../bd/global.php';
header('Access-Control-Allow-Origin: *');
//tried 1
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();
}
//tried 2
if($_POST['METHOD']=='POST_prueba'){
unset($_POST['METHOD']);
$nombre=$_POST['nombre'];
$data=json_decode($_POST['data']);
foreach ($data as $row) {
$dato1=$row['dato1'];
$dato2=$row['dato2'];
//aqui debes hacer cada inserción en base de datos
}
$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();
}
//tried 3
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($id_detalle))
{
$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");
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在将数组放入基本
示例之前尝试执行“json_encode”:
如果数据不适合数据库,请将字段从“varchar”更改为“json”,然后一切都会工作,
您的php脚本将无法工作,它有很多错误
这行代码:
$query="insert into ingresos2(nombre,dato1,dato2) 值('$nombre','$dato1','$dato2')";
应该如下所示:
在所有其他插入中,以相同的方式(如果很容易解释)
理想情况下,您应该在插入之前绑定参数这是一个例子:
try to do 'json_encode' before putting the array into the base
example :
if the data does not fit into the database, change the field from 'varchar' to 'json' , then everything will work
your php sript won't work, it has a lot of errors
This line of your code:
$query="insert into ingresos2(nombre,dato1,dato2) values ('$nombre','$dato1','$dato2')";
should look like this:
and in all other inserts the same way (if it's easy to explain)
ideally you should bind your parameters before Insert here is an example :