Foros del Web » Programando para Internet » PHP »

Actualizar datos sql con php

Estas en el tema de Actualizar datos sql con php en el foro de PHP en Foros del Web. Buenas, tengo un par de problemillas al intentar actualizar unos registros de una base de datos en sql. Lo que no funciona es que una ...
  #1 (permalink)  
Antiguo 02/05/2011, 10:35
Avatar de skamter  
Fecha de Ingreso: agosto-2009
Mensajes: 72
Antigüedad: 14 años, 7 meses
Puntos: 1
Actualizar datos sql con php

Buenas, tengo un par de problemillas al intentar actualizar unos registros de una base de datos en sql.
Lo que no funciona es que una vez mostrados los datos, no se guardan al modificarlos, es decir, se muestran los datos en el formulario pero no los guarda.
Os dejo los codigos, un saludo y a ver si alguien me puede echar una mano.

listado.php

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

$query "SELECT * FROM tabla ORDER BY marca 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>
  <?php while ($rsEmp mysql_fetch_assoc($queEmp)) { ?>
  <tr>
    <td><?php echo $rsEmp['marca']; ?></td>
    <td><?php echo $rsEmp['modelo']; ?></td>
    <td><a href="/updatep/editar.php?cf_id=<?php echo $rsEmp['cf_id']; ?>">Editar</a></td>
  </tr>
  <?php ?>
</table>
<p>&nbsp;</p>
</body>
</html>
editar.php

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

$idempresa getParam($_GET["cf_id"], "");
$action getParam($_GET["action"], "");

if (
$action == "edit") {
    
$idempresa sqlValue($_POST["cf_id"], "int");
    
$marca sqlValue($_POST["marca"], "text");
    
$modelo sqlValue($_POST["modelo"], "text");
    
$serial sqlValue($_POST["serial"], "text");
        
$email sqlValue($_POST["email"], "text");
    
$phone sqlValue($_POST["phone"], "text");
    
    
$sql "UPDATE tabla SET marca='$marca', modelo='$modelo', serial='$serial', email='$email', phone='$phone' WHERE cf_id='$idempresa'";
    
mysql_query($sql$conexion);
    
header("location: listado.php");
}

$sql "SELECT marca, modelo, serial, email, phone FROM tabla WHERE cf_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>
<form method="post" id="frEmpresa" action="editar.php?action=edit">
    <label for="nombre">marca</label>
    <input type="text" id="marca" name="marca" value="<?php echo $rsEmp["marca"]; ?>" />
    <br />
    <label for="direccion">modelo</label>
    <input type="text" id="modelo" name="modelo" value="<?php echo $rsEmp["modelo"]; ?>" />
    <br />
    <label for="telefono">serial</label>
    <input type="text" id="serial" name="serial" value="<?php echo $rsEmp["serial"]; ?>" />
    <br />
    <label for="direccion">email</label>
    <input type="text" id="email" name="email" value="<?php echo $rsEmp["email"]; ?>" />
    <br />
    <label for="direccion">phone</label>
    <input type="text" id="phone" name="phone" value="<?php echo $rsEmp["phone"]; ?>" />
    <br />
    <label for="bts">&nbsp;</label>
    <button type="submit">Guardar</button>
    <button type="reset">Limpiar</button>
    <input type="hidden" id="cf_id" name="cf_id" value="<?php echo $rsEmp["cf_id"]; ?>" />
</form>
</body>
</html>
funciones.php

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 
"int":
      
$value = ($value != "") ? "'" $value "'" "NULL";
      break;
   case 
"text":
      
$value = ($value != "") ? "'" $value "'" "NULL";
      break;
      case 
"text":
      
$value = ($value != "") ? "'" $value "'" "NULL";
      break;    
      case 
"text":
      
$value = ($value != "") ? "'" $value "'" "NULL";
      break;
          case 
"text":
      
$value = ($value != "") ? "'" $value "'" "NULL";
      break;
          case 
"text":
      
$value = ($value != "") ? "'" $value "'" "NULL";
      break;
  }
  return 
$value;
}
?>
  #2 (permalink)  
Antiguo 02/05/2011, 12:28
Avatar de xtimed  
Fecha de Ingreso: julio-2009
Ubicación: BCN - México
Mensajes: 226
Antigüedad: 14 años, 8 meses
Puntos: 41
Respuesta: Actualizar datos sql con php

Primero, no veo donde estes enviando el parametro action, para tomar los valores por url yo uso simplemente $valor = $_GET["valor"]; entonces, como no recibe el valor "action", nunca entra en tu condición y por eso no actualiza nada, eso creo yo, te faltaria agregarlo en esta linea:

Código PHP:
    <td><a href="/updatep/editar.php?cf_id=<?php echo $rsEmp['cf_id']; ?>">Editar</a></td>

//Cambiarla por 

    <td><a href="/updatep/editar.php?cf_id=<?php echo $rsEmp['cf_id']; ?>&action='edit'">Editar</a></td>
  #3 (permalink)  
Antiguo 02/05/2011, 12:33
Avatar de Sotelio  
Fecha de Ingreso: mayo-2011
Ubicación: Santiago de Chile
Mensajes: 68
Antigüedad: 12 años, 10 meses
Puntos: 21
Respuesta: Actualizar datos sql con php

Hola

Al leer los datos para editar no lees el id que luego utilizas para reconocer el registro que estás editando, por lo tanto, el campo que almacena ese valor siempre está vacío:

$sql = "SELECT marca, modelo, serial, email, phone, aqui falta cf_id FROM tabla WHERE cf_id = ".sqlValue($idempresa, "int");

Como recomendación, si el campo es el id de empresa, deberia llamarse idempresa o empresaid todo el tiempo. Si decides usar cf_id entonces que la variable que lo almacena se llame así también, por orden.

Sotelio
  #4 (permalink)  
Antiguo 02/05/2011, 12:41
Avatar de skamter  
Fecha de Ingreso: agosto-2009
Mensajes: 72
Antigüedad: 14 años, 7 meses
Puntos: 1
Respuesta: Actualizar datos sql con php

xtimed lo he probado pero nada.
Voy a probar lo que dice Sotelio a ver si hay suerte.
  #5 (permalink)  
Antiguo 02/05/2011, 12:52
Avatar de skamter  
Fecha de Ingreso: agosto-2009
Mensajes: 72
Antigüedad: 14 años, 7 meses
Puntos: 1
Respuesta: Actualizar datos sql con php

Vale, ya esta resuelto, el problema estaba en el UPDATE, lo he dajado asi y ha ido a la primera:
Código PHP:
    $sql "UPDATE tabla SET ";
    
$sql.= "marca=".$marca.", modelo=".$modelo.", serial=".$serial.", email=".$email.", phone=".$phone." ";
    
$sql.= "WHERE cf_id=".$cf_id;
    
mysql_query($sql$conexion);
    
header("location: listado.php");

Muchisimas gracias a todos por vuestra ayuda y tiempo.
Un saludo.

Etiquetas: sql
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 14:41.