PHP - Ayuda con modificar y añadir registros en tabla mysql

 
Vista:
sin imagen de perfil
Val: 5
Ha aumentado su posición en 25 puestos en PHP (en relación al último mes)
Gráfica de PHP

Ayuda con modificar y añadir registros en tabla mysql

Publicado por Agat0 (2 intervenciones) el 07/03/2021 01:58:09
Buenas estoy creando una página web de ejemplo y me he encontrado con varios problemas, y son que no puedo ni actualizar ni añadir registros a unas tablas.
He utilizado el mismo código en diferentes tablas y no habido ningún problemas pero en estas dos últimas tablas no se porque no funciona.
Tengo una tabla llamada tbl_users que sera para los administradores me deja tanto añadir como modificar y una tabla tbl_usuarios, en esta última no me deja ni modificar ni añadir ya que dice que hay un problema en la sentencia, pero no debería haber ningún problema ya que cambio algunas datos.
1
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
constants.php:
 
<?php
//Start Session
 
    define('SITEURL', 'http://localhost/biblioteca/');
    define('LOCALHOST', 'localhost');
    define('USERNAME', 'root');
    define('PASSWORD', '');
    define('DBNAME', 'fail');
?>
database.php:
 
<?php
    include('constants.php');
 
    Class Database
    {
        //Function to Connect Database
        public function db_connect()
        {
            $conn = mysqli_connect(LOCALHOST, USERNAME, PASSWORD) or die(mysqli_error());
            return $conn;
        }
 
        //Function to Select Database
        public function db_select($conn)
        {
            $db_select = mysqli_select_db($conn, DBNAME) or die(mysqli_error());
            return $db_select;
        }
 
        //Function to Select Data from Datbase
        public function select_data($tbl_name, $where="", $other="")
        {
            $query = "SELECT * FROM $tbl_name";
            if($where != "")
            {
                $query .= " WHERE $where";
            }
            if($other != "")
            {
                $query .= " $other";
            }
            return $query;
        }
 
        //Function to Insert Data into Database
        public function insert_data($tbl_name, $data)
        {
            $query = "INSERT INTO $tbl_name SET $data";
            return $query;
        }
 
        //Function to Update Data From Database
        public function update_data($tbl_name, $data, $where)
        {
            $query = "UPDATE $tbl_name SET $data WHERE $where";
            return $query;
        }
 
        //FUnction to Delete Data from Database
        public function delete_data($tbl_name, $where)
        {
            $query = "DELETE FROM $tbl_name WHERE $where";
            return $query;
        }
 
        //Function to Execute Query
        public function execute_query($conn,$query)
        {
            $res = mysqli_query($conn,$query) or die(mysqli_error($conn));
            return $res;
        }
 
        //Function to Calculate Number of Rows
        public function num_rows($res)
        {
            $num_rows = mysqli_num_rows($res);
            return $num_rows;
        }
 
        //Function to Get all the Data from DAtabase
        public function fetch_data($res)
        {
            $row = mysqli_fetch_assoc($res);
            return $row;
        }
    }
?>
edit_usuarios.php
 
<div class="body">
	<h2><?php echo $lang['edit_user'] ?></h2>
	<?php
		if(isset($_SESSION['edit']))
		{
			echo $_SESSION['edit'];
			unset($_SESSION['edit']);
		}
 
		if (isset($_GET['id']) && !empty($_GET['id'])) {
			$id = $_GET['id'];
 
			$tbl_name = 'tbl_usuarios';
			$where = "id='$id'";
 
			$query = $obj->select_data($tbl_name,$where);
			echo $query;
			$res = $obj->execute_query($conn,$query);
			if($res==true)
			{
				$count_rows = $obj->num_rows($res);
				if($count_rows==1)
				{
					$row = $obj->fetch_data($res);
					$nom_com = $row['nom_com'];
					$email = $row['email'];
					$DNI = $row['DNI'];
					$contra = $row['contra'];
 
				}
			}
		}
		else
		{
			header('location:'.SITEURL.'admin/index.php?page=users');
		}
	?>
	<form method="post" action="">
		<div class="input-group">
			<span class="input-label"><?php echo $lang['nom_com'] ?></span>
			<input class="half" type="text" name="nom_com" value="<?php echo $nom_com; ?>" required="true">
		</div>
		<div class="input-group">
			<span class="input-label"><?php echo $lang['DNI'] ?></span>
			<input class="half" type="text" name="DNI" value="<?php echo $DNI; ?>" required="true">
		</div>
 
		<div class="input-group">
			<span class="input-label"><?php echo $lang['email'] ?></span>
			<input class="half" type="email" name="email" value="<?php echo $email; ?>" required="true">
		</div>
 
 
		<div class="input-group">
			<span class="input-label"><?php echo $lang['contra'] ?></span>
			<input class="half" type="password" name="contra" value="<?php echo $contra; ?>" required="true">
		</div>
 
 
		<div class="input-group">
			<span class="input-label">
				<input type="hidden" name="id" value="<?php echo $id; ?>">
				<input class="btn-primary btn-sm" type="submit" name="submit" value="<?php echo $lang['edit_user'] ?>">
			<button type="button" class="btn-primary btn-sm" onclick="history.back()"><?php echo $lang['volver'] ?></button>
			</span>
		</div>
		<br>
	</form>
 
	<?php
		if(isset($_POST['submit']))
		{
			$id = $_POST['id'];
			$nom_com = $obj->sanitize($conn,$_POST['nom_com']);
			$DNI = $obj->sanitize($conn,$_POST['DNI']);
			$email = $obj->sanitize($conn,$_POST['email']);
			$contra = md5($obj->sanitize($conn,$_POST['contra']));
 
 
			$data = "
				nom_com='$nom_com',
				DNI='$DNI',
				email='$email',
				contra='$contra',
			";
			$tbl_name='tbl_usuarios';
			$where = "id='$id'";
			$query = $obj->update_data($tbl_name,$data,$where);
			$res = $obj->execute_query($conn,$query);
 
			if($res==true)
			{
				$_SESSION['edit'] = "<div class='success'>".$lang['edit_bien']."</div>";
				header('location:'.SITEURL.'admin/index.php?page=users2');
			}
			else
			{
				$_SESSION['edit'] = "<div class='error'>".$lang['edit_mal']."</div>";
				header('location:'.SITEURL.'admin/index.php?page=edit_user2&id='.$id);
			}
		}
	?>
edit_user.php
<div class="body">
	<h2><?php echo $lang['edit_user'] ?></h2>
	<?php
		if(isset($_SESSION['edit']))
		{
			echo $_SESSION['edit'];
			unset($_SESSION['edit']);
		}
 
		if (isset($_GET['id']) && !empty($_GET['id'])) {
			$id = $_GET['id'];
 
			$tbl_name = 'tbl_users';
			$where = "id='$id'";
 
			$query = $obj->select_data($tbl_name,$where);
 
			$res = $obj->execute_query($conn,$query);
			if($res==true)
			{
				$count_rows = $obj->num_rows($res);
				if($count_rows==1)
				{
					$row = $obj->fetch_data($res);
					$nom_com = $row['nom_com'];
					$email = $row['email'];
					$nombre = $row['nombre'];
					$contra = $row['contra'];
					$activado = $row['activado'];
				}
			}
		}
		else
		{
			header('location:'.SITEURL.'admin/index.php?page=users');
		}
	?>
	<form method="post" action="">
		<div class="input-group">
			<span class="input-label"><?php echo $lang['nom_com'] ?></span>
			<input class="half" type="text" name="nom_com" value="<?php echo $nom_com; ?>" required="true">
		</div>
 
		<div class="input-group">
			<span class="input-label"><?php echo $lang['email'] ?></span>
			<input class="half" type="email" name="email" value="<?php echo $email; ?>" required="true">
		</div>
 
		<div class="input-group">
			<span class="input-label"><?php echo $lang['nombre'] ?></span>
			<input class="half" type="text" name="nombre" value="<?php echo $nombre; ?>" required="true">
		</div>
 
		<div class="input-group">
			<span class="input-label"><?php echo $lang['contra'] ?></span>
			<input class="half" type="password" name="contra" value="<?php echo $contra; ?>" required="true">
		</div>
 
		<div class="input-group">
			<span class="input-label"><?php echo $lang['activado'] ?></span>
			<input <?php if($activado=='Yes'){echo "checked='checked'";} ?> type="radio" name="activado" value="Yes"> <?php echo $lang['si'] ?>
			<input <?php if($activado=='No'){echo "checked='checked'";} ?> type="radio" name="activado" value="No"> <?php echo $lang['no'] ?>
		</div>
 
		<div class="input-group">
			<span class="input-label">
				<input type="hidden" name="id" value="<?php echo $id; ?>">
				<input class="btn-primary btn-sm" type="submit" name="submit" value="<?php echo $lang['edit_user'] ?>">
			<button type="button" class="btn-primary btn-sm" onclick="history.back()"><?php echo $lang['volver'] ?></button>
			</span>
		</div>
		<br>
	</form>
 
	<?php
		if(isset($_POST['submit']))
		{
			$id = $_POST['id'];
			$nom_com = $obj->sanitize($conn,$_POST['nom_com']);
			$email = $obj->sanitize($conn,$_POST['email']);
			$nombre = $obj->sanitize($conn,$_POST['nombre']);
			$contra = md5($obj->sanitize($conn,$_POST['contra']));
			$activado = $_POST['activado'];
			$created_at = date('Y-m-d H:i:s');
 
			$data = "
				nom_com='$nom_com',
				email='$email',
				nombre='$nombre',
				contra='$contra',
				activado='$activado'
			";
			$tbl_name='tbl_users';
			$where = "id='$id'";
			$query = $obj->update_data($tbl_name,$data,$where);
			$res = $obj->execute_query($conn,$query);
 
			if($res==true)
			{
				$_SESSION['edit'] = "<div class='success'>".$lang['edit_bien']."</div>";
				header('location:'.SITEURL.'admin/index.php?page=users');
			}
			else
			{
				$_SESSION['edit'] = "<div class='error'>".$lang['edit_mal']."</div>";
				header('location:'.SITEURL.'admin/index.php?page=edit_user&id='.$id);
			}
		}
	?>
</div>
El error que me da es el siguiente:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE id='1'' at line 6.
Se que es bastante código pero no se porque no funciona , ya que debería funcionar cambiando algunos datos,llevo así una semana y no he encontrado la solución, espero que vosotros me ayudéis si podéis.
Un saludo.
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
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

Ayuda con modificar y añadir registros en tabla mysql

Publicado por Mauro (1036 intervenciones) el 08/03/2021 14:35:55
Hola Agat0!

Espero que ya hayas podido solucionar tu problema :(

En todo caso, para poder ayudarte sería bueno si pudieras comentar en cuál de los SQLs que muestras estás recibiendo ese error... por lo que veo en tu código parece que el problema se da en la función select_data, ¿correcto?

Algo que se me ocurre que puede estar sucediendo es que el WHERE esté quedando pegado al resto del SQL (Pienso esto porque la sentencia surge de una concatenación).

Tal vez te convendría utilizar procedimientos almacenados
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: 5
Ha aumentado su posición en 25 puestos en PHP (en relación al último mes)
Gráfica de PHP

Ayuda con modificar y añadir registros en tabla mysql

Publicado por Agat0 (2 intervenciones) el 08/03/2021 14:55:45
Ya podéis cerrar al final lo he solucionado
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