PHP - Enviar datos de filas seleccionadas por POST

 
Vista:

Enviar datos de filas seleccionadas por POST

Publicado por Brayan (1 intervención) el 11/06/2021 19:05:22
ac99fe2e568ff58a51df73821863c28c

Hola buena tarde !
Estoy tratando de enviar varios registros según los seleccionados por el check, sin embargo tengo problemas al obtener la información.
Lo que quiero es obtener los datos de la fila seleccionada e insertar en BD, podrían ayudarme por favor
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 393
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Enviar datos de filas seleccionadas por POST

Publicado por Jefferson (203 intervenciones) el 11/06/2021 21:15:32
hola amigo

Y como lo quieres hacer ? Imagino al presionar el check coja los valores de la fila, hacer un arreglo Json y luego enviar por POST para guardarlos
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
-1
Comentar
Imágen de perfil de Mauro
Val: 2.761
Oro
Ha aumentado 1 puesto en PHP (en relación al último mes)
Gráfica de PHP

Enviar datos de filas seleccionadas por POST

Publicado por Mauro (1034 intervenciones) el 14/06/2021 13:59:43
Hola Brayan:

¿Podrías mostrar algo de tu código para ver cómo lo estás encarando?

Saludos!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 393
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Enviar datos de filas seleccionadas por POST

Publicado por Jefferson (203 intervenciones) el 14/06/2021 14:28:30
Hola Maestro yo también le pregunte lo mismo al participante.

Pero sabes.? Este tema es interesante ya que muchos deseamos manejar arreglos, enviarlos por post o también para pintar un modal, bueno en fin tantas cosas...

Deja preparo un ejemplo algo rapidito para que sirva de punto de partida..
Vale me pongo a trabajar en ello...

Saludos Maestro
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 393
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Enviar datos de filas seleccionadas por POST

Publicado por Jefferson (203 intervenciones) el 14/06/2021 16:15:05
Bueno espero le sirva de punto de partida.

Copia y pega ....

el primer archivo index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>Arreglo Json</title>
</head>
 
<body>
    <section class="container-fluid">
        <h3 class="text-center">SELECCION POR CHECK DE UNA O VARIAS FILAS, ARREGLAR EN JSON Y ENVIARLA POR POST PARA INSERTAR EN BD</h3>
        <div class="table-responsive mt-3">
            <table class="table">
                <thead>
                    <tr>
                        <th scope="col">id</th>
                        <th scope="col">titulo</th>
                        <th scope="col">categoria</th>
                        <th scope="col">realizada</th>
                        <th scope="col">duracion</th>
                        <th scope="col">calificacion</th>
                        <th scope="col">formato</th>
                        <th scope="col">creada</th>
                        <th scope="col">accion</th>
                    </tr>
                </thead>
                <tbody id="table_body">
                </tbody>
            </table>
        </div>
        <button class="btn btn-success" id="envio" disabled>enviar</button>
        <div class="mt-1"><small id="recoje"></div></small>
    </section>
 
    <script>
        const arreglo = [];
        document.addEventListener('DOMContentLoaded', function() {
            let json = {
                "Harry Potter": {
                    "Harry Potter and the Sorcerers Stone": {
                        "id": 1,
                        "titulo": "Harry Potter and the Sorcerers Stone",
                        "categoria": "Fantasy",
                        "realizada": 2001,
                        "duracion": 152,
                        "calificacion": "PG",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Chamber of Secrets": {
                        "id": 2,
                        "titulo": "Harry Potter and the Chamber of Secrets",
                        "categoria": "Fantasy",
                        "realizada": 2002,
                        "duracion": 161,
                        "calificacion": "PG",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Prison of Azkaban": {
                        "id": 3,
                        "titulo": "Harry Potter and the Prison of Azkaban",
                        "categoria": "Fantasy",
                        "realizada": 2004,
                        "duracion": 142,
                        "calificacion": "PG",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Goblet of Fire": {
                        "id": 4,
                        "titulo": "Harry Potter and the Goblet of Fire",
                        "categoria": "Fantasy",
                        "realizada": 2005,
                        "duracion": 157,
                        "calificacion": "PG-13",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Order of the Phoenix": {
                        "id": 5,
                        "titulo": "Harry Potter and the Order of the Phoenix",
                        "categoria": "Fantasy",
                        "realizada": 2007,
                        "duracion": 139,
                        "calificacion": "PG-13",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Half-Blood Prince": {
                        "id": 6,
                        "titulo": "Harry Potter and the Half-Blood Prince",
                        "categoria": "Fantasy",
                        "realizada": 2009,
                        "duracion": 153,
                        "calificacion": "PG",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Deathly Hallows : Part I": {
                        "id": 7,
                        "titulo": "Harry Potter and the Deathly Hallows : Part I",
                        "categoria": "Fantasy",
                        "realizada": 2010,
                        "duracion": 146,
                        "calificacion": "PG-13",
                        "formato": "Blu-ray + DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Deathly Hallows : Part II": {
                        "id": 8,
                        "titulo": "Harry Potter and the Deathly Hallows : Part II",
                        "categoria": "Fantasy",
                        "realizada": 2011,
                        "duracion": 130,
                        "calificacion": "PG-13",
                        "formato": "Blu-ray + DVD",
                        "creada": "2015-09-25"
                    },
                    "Fantastic Beasts and Where to Find Them": {
                        "id": 9,
                        "titulo": "Fantastic Beasts and Where to Find Them",
                        "categoria": "Fantasy",
                        "realizada": 2016,
                        "duracion": 133,
                        "calificacion": "PG-13",
                        "formato": "Blu-ray + DVD",
                        "creada": "2016-08-18"
                    },
                    "Fantastic Beasts: The Crimes of Grindelwald": {
                        "id": 10,
                        "titulo": "Fantastic Beasts: The Crimes of Grindelwald",
                        "categoria": "Fantasy",
                        "realizada": 2018,
                        "duracion": 134,
                        "calificacion": "PG-13",
                        "formato": "DVD",
                        "creada": "2018-11-06"
                    }
                }
            };
            let tbody = '';
            Object.keys(json).forEach(a => {
                Object.keys(json[a]).forEach(b => {
                    let d = -1;
                    Object.keys(json[a]).forEach(c => {
                        d++;
                        tbody += '<td class="' + Object.keys(json[a][b])[d] + '">' + json[a][b][c] + '</td>';
                    })
                    tbody += '<td><input class="form-check-input" onchange="sel(this)" type="checkbox" /></td></tr>';
                    table_body.innerHTML = tbody;
                })
            })
        });
        envio.addEventListener('click', () => {
            fetch('tabla_post.php', {
                    method: 'POST',
                    body: JSON.stringify({
                        'data': arreglo
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(res => res.text())
                .then(ret =>
                    recoje.innerHTML = ret
                );
        });
        const sel = (este) => {
            if (este.checked) {
                envio.disabled = false;
                CargaJson(este, arreglo);
            } else {
                BorraJson(este, arreglo);
            }
        }
        const CargaJson = (este, arreglo) => {
            let tdlist = este.parentNode.parentNode.childNodes;
            let item = {};
            for (let h = 0; h < tdlist.length; h++) {
                var tdItem = tdlist.item(h);
                if (tdItem.className != '') {
                    item[tdItem.className] = tdItem.innerHTML;
                }
            }
            arreglo.push(item);
        }
        const BorraJson = (este, arreglo) => {
            let tdlist = este.parentNode.parentNode.childNodes;
            for (let h = 0; h < tdlist.length; h++) {
                var tdItem = tdlist.item(h);
                if (tdItem.className != '') {
                    for (let j = 0; j < arreglo.length; j++) {
                        if (arreglo[j].id == tdItem.innerHTML) {
                            arreglo.splice(j, 1)
                        }
                    }
                }
            }
            if (arreglo.length == 0) envio.disabled = true;
        }
    </script>
</body>
 
</html>


El segundo archivo que es el que recoge el post [b]tabla_post.php


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
$json = json_decode(file_get_contents('php://input'), true);
echo '<b>Recibido mediante POST</b><br>';
foreach ($json['data'] as $llave => $valor) {
    foreach ($valor as $thead => $fila) {
        if ($thead == 'id') {
            $id = $fila;
        } else if ($thead == 'titulo') {
            $titulo = $fila;
        } else if ($thead == 'categoria') {
            $categoria = $fila;
        } else if ($thead == 'realizada') {
            $realizada = $fila;
        } else if ($thead == 'duracion') {
            $duracion = $fila;
        } else if ($thead == 'calificacion') {
            $calificacion = $fila;
        } else if ($thead == 'formato') {
            $formato = $fila;
        } else if ($thead == 'creada') {
            $creada = $fila;
        }
    }
    $insert = "INSERT INTO peliculas_de_harry(id,titulo,categoria,realizada,duracion,calificacion,formato,creada)
     values('" . $id . "','" . $titulo . "','" . $categoria . "','" . $realizada . "','" . $duracion . "','" . $calificacion . "','" . $formato . "','" . $creada . "')";
    echo $insert . '<br>';
}

Si tengo errores me disculpan, lo hice muy rápido y de memoria

Saludos y suerte
Desde Venezuela
Jefferson
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 393
Ha mantenido su posición en PHP (en relación al último mes)
Gráfica de PHP

Enviar datos de filas seleccionadas por POST

Publicado por Jefferson (203 intervenciones) el 14/06/2021 16:44:50
Ooops !!

Aparentemente se entrelazaron las negritas al momento de postear el codigo en el editor del foro

archivo INDEX.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>Arreglo Json</title>
</head>
 
<body>
    <section class="container-fluid">
        <h3 class="text-center">SELECCION POR CHECK DE UNA O VARIAS FILAS, ARREGLAR EN JSON Y ENVIARLA POR POST PARA INSERTAR EN BD</h3>
        <div class="table-responsive mt-3">
            <table class="table">
                <thead>
                    <tr>
                        <th scope="col">id</th>
                        <th scope="col">titulo</th>
                        <th scope="col">categoria</th>
                        <th scope="col">realizada</th>
                        <th scope="col">duracion</th>
                        <th scope="col">calificacion</th>
                        <th scope="col">formato</th>
                        <th scope="col">creada</th>
                        <th scope="col">accion</th>
                    </tr>
                </thead>
                <tbody id="table_body">
                </tbody>
            </table>
        </div>
        <button class="btn btn-success" id="envio" disabled>enviar</button>
        <div class="mt-1"><small id="recoje"></div></small>
    </section>
 
    <script>
        const arreglo = [];
        document.addEventListener('DOMContentLoaded', function() {
            let json = {
                "Harry Potter": {
                    "Harry Potter and the Sorcerers Stone": {
                        "id": 1,
                        "titulo": "Harry Potter and the Sorcerers Stone",
                        "categoria": "Fantasy",
                        "realizada": 2001,
                        "duracion": 152,
                        "calificacion": "PG",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Chamber of Secrets": {
                        "id": 2,
                        "titulo": "Harry Potter and the Chamber of Secrets",
                        "categoria": "Fantasy",
                        "realizada": 2002,
                        "duracion": 161,
                        "calificacion": "PG",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Prison of Azkaban": {
                        "id": 3,
                        "titulo": "Harry Potter and the Prison of Azkaban",
                        "categoria": "Fantasy",
                        "realizada": 2004,
                        "duracion": 142,
                        "calificacion": "PG",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Goblet of Fire": {
                        "id": 4,
                        "titulo": "Harry Potter and the Goblet of Fire",
                        "categoria": "Fantasy",
                        "realizada": 2005,
                        "duracion": 157,
                        "calificacion": "PG-13",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Order of the Phoenix": {
                        "id": 5,
                        "titulo": "Harry Potter and the Order of the Phoenix",
                        "categoria": "Fantasy",
                        "realizada": 2007,
                        "duracion": 139,
                        "calificacion": "PG-13",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Half-Blood Prince": {
                        "id": 6,
                        "titulo": "Harry Potter and the Half-Blood Prince",
                        "categoria": "Fantasy",
                        "realizada": 2009,
                        "duracion": 153,
                        "calificacion": "PG",
                        "formato": "DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Deathly Hallows : Part I": {
                        "id": 7,
                        "titulo": "Harry Potter and the Deathly Hallows : Part I",
                        "categoria": "Fantasy",
                        "realizada": 2010,
                        "duracion": 146,
                        "calificacion": "PG-13",
                        "formato": "Blu-ray + DVD",
                        "creada": "2015-09-25"
                    },
                    "Harry Potter and the Deathly Hallows : Part II": {
                        "id": 8,
                        "titulo": "Harry Potter and the Deathly Hallows : Part II",
                        "categoria": "Fantasy",
                        "realizada": 2011,
                        "duracion": 130,
                        "calificacion": "PG-13",
                        "formato": "Blu-ray + DVD",
                        "creada": "2015-09-25"
                    },
                    "Fantastic Beasts and Where to Find Them": {
                        "id": 9,
                        "titulo": "Fantastic Beasts and Where to Find Them",
                        "categoria": "Fantasy",
                        "realizada": 2016,
                        "duracion": 133,
                        "calificacion": "PG-13",
                        "formato": "Blu-ray + DVD",
                        "creada": "2016-08-18"
                    },
                    "Fantastic Beasts: The Crimes of Grindelwald": {
                        "id": 10,
                        "titulo": "Fantastic Beasts: The Crimes of Grindelwald",
                        "categoria": "Fantasy",
                        "realizada": 2018,
                        "duracion": 134,
                        "calificacion": "PG-13",
                        "formato": "DVD",
                        "creada": "2018-11-06"
                    }
                }
            };
            let tbody = '';
            Object.keys(json).forEach(a => {
                Object.keys(json[a]).forEach(b => {
                    let d = -1;
                    Object.keys(json[a][b]).forEach(c => {
                        d++;
                        tbody += '<td class="' + Object.keys(json[a][b])[d] + '">' + json[a][b][c] + '</td>';
                    })
                    tbody += '<td><input class="form-check-input" onchange="sel(this)" type="checkbox" /></td></tr>';
                    table_body.innerHTML = tbody;
                })
            })
        });
        envio.addEventListener('click', () => {
            fetch('tabla_post.php', {
                    method: 'POST',
                    body: JSON.stringify({
                        'data': arreglo
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(res => res.text())
                .then(ret =>
                    recoje.innerHTML = ret
                );
        });
        const sel = (este) => {
            if (este.checked) {
                envio.disabled = false;
                CargaJson(este, arreglo);
            } else {
                BorraJson(este, arreglo);
            }
        }
        const CargaJson = (este, arreglo) => {
            let tdlist = este.parentNode.parentNode.childNodes;
            let item = {};
            for (let h = 0; h < tdlist.length; h++) {
                var tdItem = tdlist.item(h);
                if (tdItem.className != '') {
                    item[tdItem.className] = tdItem.innerHTML;
                }
            }
            arreglo.push(item);
        }
        const BorraJson = (este, arreglo) => {
            let tdlist = este.parentNode.parentNode.childNodes;
            for (let h = 0; h < tdlist.length; h++) {
                var tdItem = tdlist.item(h);
                if (tdItem.className != '') {
                    for (let j = 0; j < arreglo.length; j++) {
                        if (arreglo[j].id == tdItem.innerHTML) {
                            arreglo.splice(j, 1)
                        }
                    }
                }
            }
            if (arreglo.length == 0) envio.disabled = true;
        }
    </script>
</body>
 
</html>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
-1
Comentar