Error al actualizar registro en PHP con formulario

  • Autor Autor Geg1
  • Fecha de inicio Fecha de inicio

Geg1

Kappa
Verificación en dos pasos activada
Verificado por Whatsapp
¡Ha verificado su Paypal!
Verificado por Binance
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 'Garofalo, direccion=Av Libertador 879, telefono=4832658 WHERE id_cliente=2' at line 1


Me sale ese error al querer actualizar un registro mediante un formulario en PHP, el cual es este:

PHP:
<?php
mysql_pconnect("localhost", "root", "");
mysql_select_db("gestorpedidos");
mysql_query("SET NAMES 'utf8'");



$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
  $updateSQL = sprintf("UPDATE clientes SET nombre=%s, direccion=%s, telefono=%s WHERE id_cliente=%s", $_POST['nombre'], $_POST['direccion'], $_POST['telefono'], $_POST['id_cliente']);

  
  $Result1 = mysql_query($updateSQL) or die(mysql_error());

  $updateGoTo = "gestioncliente.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
}

$modif_cliente_editarcliente = "0";
if (isset($_GET['editarcliente'])) {
  $modif_cliente_editarcliente = $_GET['editarcliente'];
}

$query_editarcliente = sprintf("SELECT * FROM clientes WHERE clientes.id_cliente = %s", $modif_cliente_editarcliente);
$editarcliente = mysql_query($query_editarcliente) or die(mysql_error());
$row_editarcliente = mysql_fetch_assoc($editarcliente);
$totalRows_editarcliente = mysql_num_rows($editarcliente);


$query_clientes = "SELECT * FROM clientes ORDER BY id_cliente ASC";
$clientes = mysql_query($query_clientes) or die(mysql_error());
$row_clientes = mysql_fetch_assoc($clientes);


?>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" type="text/css" href="estilos.css">
	<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
	<title>Gestion de Clientes / Editar Cliente</title>
</head>
<body>
<form method="post" name="form1" action="<?php echo $editFormAction; ?>">
  <table align="center">
    <tr valign="baseline">
      <td nowrap align="right">Nombre:</td>
      <td><input type="text" name="nombre" value="<?php echo htmlentities($row_editarcliente['nombre'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">Direccion:</td>
      <td><input type="text" name="direccion" value="<?php echo htmlentities($row_editarcliente['direccion'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">Telefono:</td>
      <td><input type="text" name="telefono" value="<?php echo htmlentities($row_editarcliente['telefono'], ENT_COMPAT, 'utf-8'); ?>" size="32"></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">&nbsp;</td>
      <td><input type="submit" value="Actualizar Datos de Cliente"></td>
    </tr>
  </table>
  <input type="hidden" name="id_cliente" value="<?php echo $row_editarcliente['id_cliente']; ?>">
  <input type="hidden" name="MM_update" value="form1">
  <input type="hidden" name="id_cliente" value="<?php echo $row_editarcliente['id_cliente']; ?>">
</form>
<p>&nbsp;</p>
</body>
</html>
	
</body>
</html>
<?php
mysql_free_result($editarcliente);
?>


No encuentro el error sinceramente, disculpen, es que soy nuevo en estos temas
 
Insertar CODE, HTML o PHP:
$updateSQL = sprintf("UPDATE clientes SET nombre='%s', direccion='%s', telefono='%s' WHERE id_cliente='%s'", $_POST['nombre'], $_POST['direccion'], $_POST['telefono'], $_POST['id_cliente']);

si son datos de tipo string(text, varchar) debes utilizar siempre las comillas "" o ''
 

Gracias!! edite bastante el codigo y se me paso
 
En repuesta a tu mensaje privado:

Insertar CODE, HTML o PHP:
$insertarSQL = sprintf("INSERT INTO clientes (nombre, direccion, telefono) VALUES ('%s', '%s', '%s')", $_POST['nombre'], $_POST['direccion'], $_POST['telefono']);

Te doy como consejo primero investigue como se realizan las consultas mysql el uso de sprintf() es un gasto de memoria innecesario y estas exento a un XSS es decir no hay seguridad en tu código.

por otra parte los campos de auto_increment en tu caso el campo id_cliente no hace falta señalar.
 

Gracias! tendre en cuenta lo del uso del sprintf()...

Ahora tengo otra consulta..

Tengo otro formulario, el cual ingreso un producto nuevo a la base de datos, un formulario en el cual tambien incluyo la categoria del producto ya seteada por medio de un <option ....

Pero no me relaciona las tablas ya que me sale solo una categoria y repetida y ademas, luego de ingresarlo me da este error:


PHP:
<?php
mysql_pconnect("localhost", "root", "");
mysql_select_db("gestorpedidos");
mysql_query("SET NAMES 'utf8'");


    $formulario = $_SERVER['PHP_SELF']; 
    if (isset($_SERVER['QUERY_STRING'])) { 
        $formulario.= "?" . htmlentities($_SERVER['QUERY_STRING']); 
    } 

    if ((isset($_POST["insertar"])) && ($_POST["insertar"] == "formularioproductos")) { 
        $insertarSQL = sprintf("INSERT INTO productos (id_producto, producto, descripcion_p, precio) VALUES (null, '%s', '%s', '%s')", $_POST['producto'], $_POST['descripcion_p'], $_POST['precio']); 

        $resultado = mysql_query($insertarSQL) or die(mysql_error()); 
        
        if ($resultado == true) {
        	$insertarSQL2 = sprintf("INSERT INTO categorias (id_categoria, categoria) VALUES (null, '%s')", $_POST['categoria']); 
        }

        $luegoir = "pedidos.php"; 

        if (isset($_SERVER['QUERY_STRING'])) { 
            $luegoir.= (strpos($luegoir, '?')) ? "&" : "?"; 
            $luegoir.= $_SERVER['QUERY_STRING']; 
        } 

        header(sprintf("Location: %s", $luegoir)); 
    } 



$query_nuevoproducto = "SELECT * FROM productos INNER JOIN categorias ON productos.categoria_id = categorias.id_categoria";
$nuevoproducto = mysql_query($query_nuevoproducto) or die(mysql_error());
$row_nuevoproducto = mysql_fetch_assoc($nuevoproducto);

?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="estilos.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<title>Ingresar Nuevo Producto</title>
</head>

<body>
<form action="<?php echo $formulario; ?>" method="post" name="formularioproductos" id="formularioproductos">
  <table align="center">
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Categoria:</td>
      <td><select name="categoria_id" size="1">
        <option value="" >Seleccionar</option>
        <?php
do {  
?>
        <option value="<?php echo $row_nuevoproducto['categoria_id']?>"><?php echo $row_nuevoproducto['categoria']?></option>
        <?php
} while ($row_nuevoproducto = mysql_fetch_assoc($nuevoproducto));
  $rows = mysql_num_rows($nuevoproducto);
  if($rows > 0) {
      mysql_data_seek($nuevoproducto, 0);
	  $row_nuevoproducto = mysql_fetch_assoc($nuevoproducto);
  }
?>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Producto:</td>
      <td><input type="text" name="direccion" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Descripcion:</td>
      <td><input type="text" name="descripcion" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Precio:</td>
      <td><input type="text" name="precio" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">&nbsp;</td>
      <td align="center"><input class="boton" type="submit" value="Ingresar nuevo Producto" /></td>
    </tr>
  </table>
  <input type="hidden" name="insertar" value="formularioproductos" />
</form>
<p>&nbsp;</p>
</body>
</html>

<?php
  mysql_free_result($nuevoproducto);
 
?>
 
Última edición: