简体   繁体   English

用PHP无法更新MySQL数据库

[英]Cant update mysql database with php

I really dont know whats wrong with it, i can generate data with a similar php and another nearly identical without the $categoria = $_POST["CAT"]; 我真的不知道这是怎么回事,我可以使用类似的php和另一个几乎相同的数据生成数据,而无需$ categoria = $ _POST [“ CAT”]; and $sql .= "SET catPERS='$categoria' "; 和$ sql。=“ SET catPERS ='$ categoria'”; (there is some spanish in it, ill translate if you need it) (其中有一些西班牙语,如果需要的话请翻译)

<?php
// PROCESO PERSONAS UPD (ACTUALIZACION)

// CONECTAR AL SERVIDOR DE BASE DE DATOS
$conex = mysql_connect("localhost","root","");

// CONTROLAR CONEXION
if (!$conex) {
    die("ATENCION!!!.. NO se pudo CONECTAR al SERVIDOR de Bae de Datos");
} // endif

// SELECCIONAR BASE DE DATOS
$selDB = mysql_select_db("database",$conex);

// CONTROLAR SELECCION DE BASE DE DATOS
if (!$selDB) {
    die("ATENCION!!!.. NO se pudo SELECCIONAR Base de Datos");
} // endif

// CAPTURAR DATOS DEL FORMULARIO
$id             = $_POST["ID"];
$nombre         = $_POST["NOM"];
$direccion      = $_POST["DIR"];
$telefono       = $_POST["TEL"];
$departamento   = $_POST["DTO"];
$categoria      = $_POST["CAT"];     

// CREAR SENTENCIA SQL PARA ACTUALIZACION
$sql  = "UPDATE Personas ";
$sql .= "SET nomPERS='$nombre', ";
$sql .= "SET dirPERS='$direccion', ";
$sql .= "SET telPERS='$telefono', ";
$sql .= "SET dtoPERS='$departamento', ";
$sql .= "SET catPERS='$categoria' ";
$sql .= "WHERE idPERS=$id";

// die($sql);

// EJECUTAR SENTENCIA SQL
mysql_query($sql,$conex); 

// CERRAR CONEXION
mysql_close($conex);

// VOLVER AUTOMATICAMENTE AL FORMULARIO DE ACTUALIZACIÓN (REDIRIGIR)
header("Location: productos.html");
?>

在更新查询中更新多个值时, 只需一个 SET关键字,并用逗号分隔其他值。

It's a bad idea to use mysql_ as it's currently deprecated. 使用mysql_是一个坏主意,因为它已被弃用。 Furthermore, your query string is vulnerable to SQL injection. 此外,您的查询字符串容易受到SQL注入的攻击。 Time to step up your game, Santiago. 是时候加强您的游戏了,圣地亚哥。

$mysqli = new mysqli('localhost', 'user', 'pass', 'database');

if($stmt = $mysqli->prepare("update Personas set nomPERS = ?, dirPERS = ?, telPERS = ?, dtoPERS = ?, catPERS = ?, where idPERS = ?")):
    $stmt->bind_param('sssssi', $_POST['ID'], $_POST['NOM'], $_POST['DIR'], $_POST['TEL'], $_POST['DTO'], $_POST['CAT'], $id);

    if($stmt->execute()):
         $stmt->close();
         header("Location: productos.html");
    endif;
endif;

This is the safe way. 这是安全的方法。 It will also resolve issues with your (currently) broken SQL query. 它还可以解决您(当前)断开的SQL查询的问题。

By using prepared statements in mysqli we're avoiding SQL injection that is possible in your current code. 通过在mysqli中使用准备好的语句,我们避免了当前代码中可能发生的SQL注入。

Links 链接

  1. MySQLI 库MySQLi
  2. Prepared Statements 准备的陈述
  3. Binding Parameters 绑定参数
  4. execute() 执行()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM