Problem with mysql sentence in php

2

It does not give me any errors but it does not upload me to the database.

If I put quotation marks of a '' I get a syntax error in $ name but if I put "" it does not give me an error but it does not upload anything to the database either.

       mysqli_query($conect, "INSERT INTO Clientes 
    (nombre,apellido,direccion,provincia,ciudad,zip,fono,email) VALUES 
    ('$nombre', '$apellido', '$direccion', '$provincia', '$ciudad', 
     '$zip', '$fono', '$email')");
    
asked by Vinicio Moya Almeida 23.10.2017 в 10:03
source

1 answer

3

The first problem you suffer ( if I put quotation marks on a '' I get syntax error in $nombre but if I put "" I do not get an error but nothing goes up in the database ) is because the single quotes do not interpret the content of the variables within a string, with double quotes yes.

Also, if you put single quotes you should escape the single quotes that delimit the variables or they will be understood as part of PHP and not SQL:

$a = '('$pepito')';

After the string '(' there is a variable without an intermediate operator, the same happens with the final string ')'. The correct way to escape simple quotes would be:

$a = '(\'$pepito\')';

Your code has no error control, so if the query is producing a syntax error, duplicate key, etc., you will not hear about the problem.

Furthermore, it is a bad practice to introduce variables directly into an SQL query. You could suffer SQL syntax problems if any contain special characters such as single quotes or others, opening the door to SQL injection attacks that are a very serious problem to take into consideration .

Proposed solution

If you do not want to use queries prepared with mysqli_prepare() then I recommend you escape the contents of the variables with mysqli_real_escape_string() .

/* Escapamos caracteres especiales de todas las cadenas agregadas al SQL */
$resultado = mysqli_query(
  $conect,
  "
    INSERT INTO Clientes 
    (
      nombre,
      apellido,
      direccion,
      provincia,
      ciudad,
      zip,
      fono,
      email
    ) VALUES (
      '" . mysqli_real_escape_string($conect, $nombre) . "',
      '" . mysqli_real_escape_string($conect, $apellido) . "',
      '" . mysqli_real_escape_string($conect, $direccion) . "',
      '" . mysqli_real_escape_string($conect, $provincia) . "',
      '" . mysqli_real_escape_string($conect, $ciudad) . "',
      '" . mysqli_real_escape_string($conect, $zip) . "',
      '" . mysqli_real_escape_string($conect, $fono) . "',
      '" . mysqli_real_escape_string($conect, $email) . "'
    )
  "
);
/* En caso de haberse producido algún error durante la ejecución de
     la consulta anterior mostramos el mensaje de error */
if ($resultado === false) {
  die('ERROR SQL: ' . mysqli_error($conect));
}
    
answered by 23.10.2017 в 11:08