Foros del Web » Programando para Internet » PHP »

Problemas para editar en mysql

Estas en el tema de Problemas para editar en mysql en el foro de PHP en Foros del Web. Hola tengo problemas para editar en mysql como lo dice el titulo, si puedo insertar, buscar pero no editar les cuento lo que me pasa, ...
  #1 (permalink)  
Antiguo 09/04/2012, 10:29
 
Fecha de Ingreso: abril-2012
Ubicación: minas
Mensajes: 10
Antigüedad: 12 años
Puntos: 0
Problemas para editar en mysql

Hola tengo problemas para editar en mysql como lo dice el titulo, si puedo insertar, buscar pero no editar les cuento lo que me pasa, tengo un codigo en php que al ejecutarlo me envia constantemente a otra pagina que se llama listado.php en la cual me aparecen usuarios y el boton editar pero al apretar en ese boton solo me deja en la misma pagina es como una cadena abierta sin fin, les dejo el codigo a ver que piensan que es:[CODE]

Código
Código PHP:
:
       include(
"include/conexion.php"); 
    include(
"include/funciones.php"); 

    
$idempresa getParam($_GET["id"], "-1"); 
    
$action getParam($_GET["action"], ""); 

    if (
$action == "edit") { 
        
$idempresa sqlValue($_POST["id"], "int"); 
        
$nombre sqlValue($_POST["nombre"], "text"); 
        
$direccion sqlValue($_POST["direccion"], "text"); 
        
$telefono sqlValue($_POST["telefono"], "int"); 
         
        
$sql "UPDATE empresa SET "
        
$sql.= "nombre=".$nombre.", direccion=".$direccion.", telefono=".$telefono." "
        
$sql.= "WHERE id=".$idempresa
        
mysql_query($sql$conexion); 
        
header("location: listado.php"); 
    } 

    
$sql "SELECT * FROM empresa WHERE id = ".sqlValue($idempresa"int"); 
    
$queEmp mysql_query($sql$conexion); 
    
$rsEmp mysql_fetch_assoc($queEmp); 
    
$total mysql_num_rows($queEmp); 
    if (
$total == 0) { 
        
header("location: listado.php"); 
        exit; 
    } 
ese es el codigo para editar y ahora pongo el codigo del listado:


Código PHP:
Código PHP:
<?php 
    
require("include/conexion.php"); 
    require(
"include/funciones.php"); 

    
$query "SELECT * FROM empresa ORDER BY nombre ASC"
    
$queEmp mysql_query($query$conexion); 
    
?> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
    <title>Listado de Empresas</title> 
    <link href="styles.css" rel="stylesheet" type="text/css" /> 
    </head> 
    <body> 
    <h3>Listado de  Empresas</h3> 
    <table width="600" border="0" cellspacing="0" cellpadding="0"> 
      <tr> 
        <th>Nombre</th> 
        <th>Dirección</th> 
        <th>&nbsp;</th> 
      </tr> 
      <?php while ($rsEmp mysql_fetch_assoc($queEmp)) { ?> 
      <tr> 
        <td><?php echo $rsEmp['nombre']; ?></td> 
        <td><?php echo $rsEmp['direccion']; ?></td> 
        <td><a href="editar.php?id=<?php echo $rsEmp['id']; ?>">Editar</a></td> 
      </tr> 
      <?php ?> 
    </table> 
    <p>&nbsp;</p> 
    </body> 
    </html>
opinen que tan mal esta todo obvio que tiene muchas cosas para pulir, igual necesito que funcione por ahora.

Última edición por ggtc; 09/04/2012 a las 11:33
  #2 (permalink)  
Antiguo 09/04/2012, 11:40
Avatar de Triby
Mod on free time
 
Fecha de Ingreso: agosto-2008
Ubicación: $MX->Gto['León'];
Mensajes: 10.106
Antigüedad: 15 años, 8 meses
Puntos: 2237
Respuesta: Problemas para editar en mysql

Aparentemente el enlace a editar.php es correcto, muestra el código fuente generado en el navegador, seguro ahí se puede ver mejor el error.
__________________
- León, Guanajuato
- GV-Foto
  #3 (permalink)  
Antiguo 09/04/2012, 12:01
Avatar de p414  
Fecha de Ingreso: agosto-2009
Ubicación: casi casi casi... a un lado de la cuna...
Mensajes: 575
Antigüedad: 14 años, 7 meses
Puntos: 44
Respuesta: Problemas para editar en mysql

creo que tu problema es con los tipos de datos que envias trata cambiando esta linea

Código PHP:
Ver original
  1. $sql.= "nombre='".$nombre."', direccion='".$direccion."', telefono=".$telefono." ";

y si aun asi no te funciona prueba con esta linea y nos indicas el error

Código PHP:
Ver original
  1. mysql_query($sql, $conexion) or die (mysql_error() );
  #4 (permalink)  
Antiguo 09/04/2012, 20:21
 
Fecha de Ingreso: abril-2012
Ubicación: minas
Mensajes: 10
Antigüedad: 12 años
Puntos: 0
Respuesta: Problemas para editar en mysql

Cita:
Iniciado por p414 Ver Mensaje
creo que tu problema es con los tipos de datos que envias trata cambiando esta linea

Código PHP:
Ver original
  1. $sql.= "nombre='".$nombre."', direccion='".$direccion."', telefono=".$telefono." ";

y si aun asi no te funciona prueba con esta linea y nos indicas el error

Código PHP:
Ver original
  1. mysql_query($sql, $conexion) or die (mysql_error() );
Estos son los errores que me tira:
Notice: Undefined index: action in C:\xampp\htdocs\proyecto\editar.php on line 7

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\proyecto\editar.php on line 24

Warning: mysql_affected_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\proyecto\editar.php on line 25
Unknown column 'id' in 'where clause' no se que hago mal.
  #5 (permalink)  
Antiguo 10/04/2012, 09:17
Avatar de p414  
Fecha de Ingreso: agosto-2009
Ubicación: casi casi casi... a un lado de la cuna...
Mensajes: 575
Antigüedad: 14 años, 7 meses
Puntos: 44
Respuesta: Problemas para editar en mysql

Notice: Undefined index: action in C:\xampp\htdocs\proyecto\editar.php on line 7

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\proyecto\editar.php on line 24


ok aki te indica que no ha recibido ningun valor por lo tanto no puede ejecutarse

Warning: mysql_affected_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\proyecto\editar.php on line 25


esto es exactamente lo mismo que el anterior



Unknown column 'id' in 'where clause'

y aqui te indica que no existe la columna "id", podrias indicar tu BD ????
  #6 (permalink)  
Antiguo 10/04/2012, 12:26
 
Fecha de Ingreso: abril-2012
Ubicación: minas
Mensajes: 10
Antigüedad: 12 años
Puntos: 0
Respuesta: Problemas para editar en mysql

Cita:
Iniciado por p414 Ver Mensaje
Notice: Undefined index: action in C:\xampp\htdocs\proyecto\editar.php on line 7

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\proyecto\editar.php on line 24


ok aki te indica que no ha recibido ningun valor por lo tanto no puede ejecutarse

Warning: mysql_affected_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\proyecto\editar.php on line 25


esto es exactamente lo mismo que el anterior



Unknown column 'id' in 'where clause'

y aqui te indica que no existe la columna "id", podrias indicar tu BD ????

ya pude sacar unos de los errores pero ahora me sigue tirando estos 2 :

Notice: Undefined index: action in C:\xampp\htdocs\proyecto\editar.php on line 7

Warning: mysql_affected_rows(): supplied resource is not a valid MySQL-Link resource in C:\xampp\htdocs\proyecto\editar.php on line 25


la base de datos:
CREATE TABLE IF NOT EXISTS `empresa` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(100) NOT NULL,
`direccion` varchar(100) NOT NULL,
`telefono` int(8) NOT NULL,
`imagen` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=39 ;
  #7 (permalink)  
Antiguo 10/04/2012, 12:52
Avatar de p414  
Fecha de Ingreso: agosto-2009
Ubicación: casi casi casi... a un lado de la cuna...
Mensajes: 575
Antigüedad: 14 años, 7 meses
Puntos: 44
Respuesta: Problemas para editar en mysql

Código PHP:
Ver original 


donde ocupas eso??? sabes que hace??? de no ser así te recomiendo que leeas el manual de PHP


Código PHP:
Ver original
  1. Notice: Undefined index: action in C:\xampp\htdocs\proyecto\editar.php on line 7

aqui te dice que no has definido una variable llamada action... porque no nos muestras algo de código...
  #8 (permalink)  
Antiguo 10/04/2012, 14:31
 
Fecha de Ingreso: abril-2012
Ubicación: minas
Mensajes: 10
Antigüedad: 12 años
Puntos: 0
Respuesta: Problemas para editar en mysql

Cita:
Iniciado por p414 Ver Mensaje
Código PHP:
Ver original 


donde ocupas eso??? sabes que hace??? de no ser así te recomiendo que leeas el manual de PHP


Código PHP:
Ver original
  1. Notice: Undefined index: action in C:\xampp\htdocs\proyecto\editar.php on line 7

aqui te dice que no has definido una variable llamada action... porque no nos muestras algo de código...
yo a mysql_affected_rows lo utilizo para que me de las ultimas filas afectadas por el UPDATE osea las editadas. paso algo de codigo:
Concexion:
Código PHP:
<?php
$conexion 
mysql_connect("localhost""gonza""") or trigger_error(mysql_error(),E_USER_ERROR); 
mysql_select_db("practica"$conexion);
?>
Funciones:
Código PHP:
<?php
function getParam($param$default) {
    
$result $default;
    if (isset(
$param)) {
          
$result = (get_magic_quotes_gpc()) ? $param addslashes($param);
    }
    return 
$result;
}
function 
sqlValue($value$type) {
  
$value get_magic_quotes_gpc() ? stripslashes($value) : $value;
  
$value function_exists("mysql_real_escape_string") ? mysql_real_escape_string($value) : mysql_escape_string($value);
  switch (
$type) {
    case 
"text":
      
$value = ($value != "") ? "'" $value "'" "NULL";
      break;
    case 
"int":
      
$value = ($value != "") ? intval($value) : "NULL";
      break;
    case 
"double":
      
$value = ($value != "") ? "'" doubleval($value) . "'" "NULL";
      break;
    case 
"date":
      
$value = ($value != "") ? "'" $value "'" "NULL";
      break;
  }
  return 
$value;
}
?>
Editar que estoy utilizando ahora:
Código PHP:
<?php
require("include/conexion.php");
require(
"include/funciones.php");

$idempresa getParam($_GET["id"], "-1");
$action getParam($_GET["action"], "");

if (
$action == "edit") {
    
$idempresa sqlValue($_POST["id"], "int");
    
$nombre sqlValue($_POST["nombre"], "text");
    
$direccion sqlValue($_POST["direccion"], "text");
    
$telefono sqlValue($_POST["telefono"], "int");
    
    
$sql "UPDATE empresa SET ";
    
$sql.= "nombre=".$nombre.", direccion=".$direccion.", telefono=".$telefono." ";
    
$sql.= "WHERE id=".$idempresa;
    
mysql_query($sql$conexion);
    
header("location: listado.php");
}

$sql "SELECT * FROM empresa WHERE id = ".sqlValue($idempresa"int");
$queEmp mysql_query($sql$conexion);
$rsEmp mysql_fetch_assoc($queEmp);
$total mysql_num_rows($queEmp);
if (
$total == 0) {
    
header("location: listado.php");
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>PHP con MySQL: Editar datos en MySQL</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h3>Editar Empresa</h3>
<form method="post" id="frEmpresa" action="editar.php?action=edit">
    <label for="nombre">Nombre</label>
    <input type="text" id="nombre" name="nombre" value="<?php echo $rsEmp["nombre"]; ?>" />
    <br />
    <label for="direccion">Direcci&oacute;n</label>
    <input type="text" id="direccion" name="direccion" value="<?php echo $rsEmp["direccion"]; ?>" />
    <br />
    <label for="telefono">Telefono</label>
    <input type="text" id="telefono" name="telefono" value="<?php echo $rsEmp["telefono"]; ?>" />
    <br />
    <label for="bts">&nbsp;</label>
    <button type="submit">Guardar</button>
    <button type="reset">Limpiar</button>
    <input type="hidden" id="id" name="id" value="<?php echo $rsEmp["id"]; ?>" />
</form>
</body>
</html>
Listado:
Código PHP:
<?php
    
require("include/conexion.php");
    require(
"include/funciones.php");

    
$query "SELECT * FROM empresa ORDER BY nombre ASC";
    
$queEmp mysql_query($query$conexion);
    
?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Listado de Empresas</title>
    <link href="styles.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <h3>Listado de  Empresas</h3>
    <table width="600" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <th>Nombre</th>
        <th>Dirección</th>
        <th>&nbsp;</th>
      </tr>
      <?php while ($rsEmp mysql_fetch_assoc($queEmp)) { ?>
      <tr>
        <td><?php echo $rsEmp['nombre']; ?></td>
        <td><?php echo $rsEmp['direccion']; ?></td>
        <td><a href="editar.php?id=<?php echo $rsEmp['id']; ?>">Editar</a></td>
      </tr>
      <?php ?>
    </table>
    <p>&nbsp;</p>
    </body>
    </html>
ahora todo esto solo me tira un error: Notice: Undefined index: action in C:\xampp\htdocs\proyecto\editar.php on line 6
  #9 (permalink)  
Antiguo 10/04/2012, 15:54
Avatar de p414  
Fecha de Ingreso: agosto-2009
Ubicación: casi casi casi... a un lado de la cuna...
Mensajes: 575
Antigüedad: 14 años, 7 meses
Puntos: 44
Respuesta: Problemas para editar en mysql

Código PHP:
Ver original
  1. $action = getParam($_GET["action"], "");

esa es la línea 6... tengo una duda... logra hacer la actualización???

y si le cambias a tu archivo listado.php esta linea creo que dejaría de enviar ese error

Código PHP:
Ver original
  1. <td><a href="editar.php?id=<?php echo $rsEmp['id']; ?>&action=edit">Editar</a></td>

aunque no entiendo para que haces la validación si nunca envías esa variable :S
  #10 (permalink)  
Antiguo 10/04/2012, 17:00
 
Fecha de Ingreso: abril-2012
Ubicación: minas
Mensajes: 10
Antigüedad: 12 años
Puntos: 0
Respuesta: Problemas para editar en mysql

Cita:
Iniciado por p414 Ver Mensaje
Código PHP:
Ver original
  1. $action = getParam($_GET["action"], "");

esa es la línea 6... tengo una duda... logra hacer la actualización???

y si le cambias a tu archivo listado.php esta linea creo que dejaría de enviar ese error

Código PHP:
Ver original
  1. <td><a href="editar.php?id=<?php echo $rsEmp['id']; ?>&action=edit">Editar</a></td>

aunque no entiendo para que haces la validación si nunca envías esa variable :S
Me da ese error tanto en linea 5 como en 6 de editar.php pero me cumple la funcion de editar de todos modos
  #11 (permalink)  
Antiguo 10/04/2012, 17:05
Avatar de p414  
Fecha de Ingreso: agosto-2009
Ubicación: casi casi casi... a un lado de la cuna...
Mensajes: 575
Antigüedad: 14 años, 7 meses
Puntos: 44
Respuesta: Problemas para editar en mysql

Código PHP:
Ver original
  1. <?php
  2. require("include/conexion.php");
  3. require("include/funciones.php");
  4. $action = "";

Agrega esta linea y dinos que tal te va


yo vuelvo en una hora aprox para que cuentes como te fue
__________________
Desde hace tiempo estoy esperandote... bienvenido mi pequeño Diego!!!
  #12 (permalink)  
Antiguo 10/04/2012, 18:58
 
Fecha de Ingreso: abril-2012
Ubicación: minas
Mensajes: 10
Antigüedad: 12 años
Puntos: 0
Respuesta: Problemas para editar en mysql

Cita:
Iniciado por p414 Ver Mensaje
Código PHP:
Ver original
  1. <?php
  2. require("include/conexion.php");
  3. require("include/funciones.php");
  4. $action = "";

Agrega esta linea y dinos que tal te va


yo vuelvo en una hora aprox para que cuentes como te fue
Ya estoy por dejar no puedo con ese error del action probe lo que dijistes pero no funciona me sigue dando ese error:
Notice: Undefined index: action in C:\xampp\htdocs\proyecto\editar.php on line 7

ademas no quiero molestarte mas veré como lo puedo solucionar mas adelante gracias por todo.
  #13 (permalink)  
Antiguo 11/04/2012, 21:08
Avatar de p414  
Fecha de Ingreso: agosto-2009
Ubicación: casi casi casi... a un lado de la cuna...
Mensajes: 575
Antigüedad: 14 años, 7 meses
Puntos: 44
Respuesta: Problemas para editar en mysql

como que no te va???? si antes de usar tu variable $action (la cual no la tenias declara) la declaras no debes tener problemas :S


a ver cambia esta linea

Código PHP:
Ver original
  1. $action = getParam($_GET["action"], "");

por

Código PHP:
Ver original
  1. $action = $_GET["action"];

y a tu archivo listado ponle esto

Código PHP:
Ver original
  1. <td><a href="editar.php?id=<?php echo $rsEmp['id']; ?>&action=edit">Editar</a></td>

y dinos que tal te va
__________________
Desde hace tiempo estoy esperandote... bienvenido mi pequeño Diego!!!
  #14 (permalink)  
Antiguo 12/04/2012, 15:30
 
Fecha de Ingreso: abril-2012
Ubicación: minas
Mensajes: 10
Antigüedad: 12 años
Puntos: 0
Respuesta: Problemas para editar en mysql

Si cambio eso como tu me dices al hacer click en editar no me lleva a editar solo queda en listado
  #15 (permalink)  
Antiguo 13/04/2012, 09:06
Avatar de p414  
Fecha de Ingreso: agosto-2009
Ubicación: casi casi casi... a un lado de la cuna...
Mensajes: 575
Antigüedad: 14 años, 7 meses
Puntos: 44
Respuesta: Problemas para editar en mysql

pues si, en el archivo editar.php tienes este if

Código PHP:
Ver original
  1. if ($action == "edit") {
  2.     $idempresa = sqlValue($_POST["id"], "int");
  3.     $nombre = sqlValue($_POST["nombre"], "text");
  4.     $direccion = sqlValue($_POST["direccion"], "text");
  5.     $telefono = sqlValue($_POST["telefono"], "int");
  6.    
  7.     $sql = "UPDATE empresa SET ";
  8.     $sql.= "nombre=".$nombre.", direccion=".$direccion.", telefono=".$telefono." ";
  9.     $sql.= "WHERE id=".$idempresa;
  10.     mysql_query($sql, $conexion);
  11.     header("location: listado.php");
  12. }

y en el tienes un redireccionamiento, trata quitando ese redireccionamiento y dinos que tal va
__________________
Desde hace tiempo estoy esperandote... bienvenido mi pequeño Diego!!!

Etiquetas: edición, mysql, update
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 09:43.