php - Problems inserting MYSQL data

5

Good, I am trying to insert data from my form, but when I press the submit button it sends me the message of:

"Connection made"

What is the message of my php file of connection , nothing more. The code to insert I have it in another file. This is my code.

The one in my form venta_cliente.php :

<div class="container clear_both padding_fix">
        <!--\\\\ container  start \\\-->



        <form action="php/registrar_cliente.php" method="POST">

                <div class="form-group">
                  <label for="idnom">Nombre:</label>
                  <input type="text" class="form-control" id="idnom" name="nnombre" REQUIRED placeholder="Ingresar Nombre">
                </div>

                <div class="form-group">
                  <label for="idape">Apellidos:</label>
                  <input type="text" class="form-control" id="idape" name="napellido" REQUIRED placeholder="Ingresar Apellidos">
                </div>

              <div class="form-group">
                <label for="idtdoc">Tipo de Documento:</label>
                <select class="form-control" id="idtdoc" name="ntdoc">
                  <option value="DNI">DNI</option>
                  <option value="RUC">RUC</option>
                </select>
              </div>



                <div class="form-group">
                  <label for="iddoc">Documento:</label>
                  <input type="text" class="form-control" id="iddoc" name="ndoc" REQUIRED placeholder="Numero de Documento">
                </div>


              <div class="row">

                <div class="form-group col-sm-4">
                  <label for="iddir">Direccion:</label>
                  <input type="text" class="form-control" id="iddir" name="ndireccion" REQUIRED placeholder="Ingresar Direccion">
                </div>

                <div class="form-group col-sm-8">
                  <label for="idtelf">Telf/Movil:</label>
                  <input type="text" class="form-control" id="idtelf" name="ntelf" REQUIRED placeholder="Ingresar Telf o Movil">
                </div>

              </div>


                <input type="submit" class="btn btn-primary" value="Registrar"></button>
            <button type="button" class="btn btn-default">Cancelar</button>

        </form>


      </div>
      <!--\\\\ container  end \\\-->

And this is the code of my file to register register_client.php :

<?php 
include'conexion.php';

$nombre=$_POST['nnombre'];
$apellido=$_POST['napellido'];  
$tipo_doc=$_POST['ntdoc'];
$documento=$_POST['ndoc'];
$direccion=$_POST['ndireccion'];
$telf=$_POST['ntelf'];

if(isset($_POST['submit'])){

$sql = "INSERT INTO cliente (nombre, apellidos, tipo_doc, dni, direccion, telfmovil)
VALUES ('$nombre', '$apellido', '$tipo_doc', '$documento', '$direccion', '$telf')";

if ($conn->query($sql) === TRUE) {
    echo "Datos registrados correctamente";
} else {
    echo "Ups! Error: " . $sql . "<br>" . $conn->error;
}

}

$conn->close();

 ?>

And the code of my file conexion.php :

<?php
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "dbagricola";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

if (mysqli_connect_error()) {
    die("Conexion a la Base de Dato fallida:  " . mysqli_connect_error());
}

echo "Conexion hecha";


?>

The files register_client.php and conexion.php are hosted in a folder called PHP, does that affect to insert the data?

If you know what my mistake is, I would be very grateful to have it seen to correct it.

    
asked by Raphael 16.06.2016 в 05:50
source

2 answers

10

The problem I see is:

if(isset($_POST['submit'])){//Esta variable no existe

To work with what you have, you should add the following to the form:

 <input type="submit" class="btn btn-primary" name="submit" value="Registrar">

I hope it serves you

    
answered by 16.06.2016 / 07:12
source
6

I will answer your additional reward, since the answer that is accepted is clear and correct, the code PHP I have advanced a bit, which is the part that I see too vulnerable, a case of the current code, I do not see the logic of directly obtaining the data from the form without checking in PHP .

In this case we could do before a check if our form is defined and check that no field (input) is empty, and otherwise it would get the data.

To obtain the data, I would use mysqli_real_escape_string() , when one uses sentences mysqli , in case of using statements prepare() it would not be correct to use this function.

mysqli_real_escape_string - It escapes the special characters of a string to be used in an SQL statement, taking into account the current character set of the connection

Example :

$nombre = mysqli_real_escape_string($conn, $_POST['nnombre']);
  

Note: We could do more checks if you want to implement more security, such as counting the minimum and maximum characters of a string obtained from the form or some expresión regular PHP to validate the DNI documents, etc.

As you mentioned, it is better to create sentencias preparadas to better protect our statements against attacks of inyección SQL

Attacks of inyección SQL can only occur if we do not format the parts of our query in an invulnerable way.

A serious malicious format:

SELECT * FROM usuario WHERE nombre='Foo';

A correct format would be:

SELECT * FROM usuario WHERE nombre='Foo\'; 

Source (English):

Source SOes:

Example prepared statements :

HTML Code:

  

Note: The attribute name is our identifier, to obtain our data according to case by method POST or GET , in our case it will be by method POST .

<form action="php/registrar_cliente.php" method="POST">

   <div class="form-group">
      <label for="idnom">Nombre:</label>
      <input type="text" class="form-control" id="idnom" name="nnombre" REQUIRED placeholder="Ingresar Nombre">
   </div>

   <div class="form-group">
      <label for="idape">Apellidos:</label>
      <input type="text" class="form-control" id="idape" name="napellido" REQUIRED placeholder="Ingresar Apellidos">
   </div>

   <div class="form-group">
      <label for="idtdoc">Tipo de Documento:</label>
      <select class="form-control" id="idtdoc" name="ntdoc">
         <option value="DNI">DNI</option>
         <option value="RUC">RUC</option>
      </select>
   </div>

   <div class="form-group">
      <label for="iddoc">Documento:</label>
      <input type="text" class="form-control" id="iddoc" name="ndoc" REQUIRED placeholder="Numero de Documento">
    </div>

    <div class="row">
        <div class="form-group col-sm-4">
            <label for="iddir">Direccion:</label>
            <input type="text" class="form-control" id="iddir" name="ndireccion" REQUIRED placeholder="Ingresar Direccion">
         </div>

         <div class="form-group col-sm-8">
            <label for="idtelf">Telf/Movil:</label>
            <input type="text" class="form-control" id="idtelf" name="ntelf" REQUIRED placeholder="Ingresar Telf o Movil">
          </div>

     </div>    

     <input type="submit" name="registrar" class="btn btn-primary" value="Registrar">
     <button type="button" class="btn btn-default">Cancelar</button>

</form> 

PHP Code (php / register_client.php)

<?php

//Reseteo variables.
$msg = $nombre = $apellido = $tipo_doc = $documento = $direccion = $telf = NULL;

//Comprobación definición formulario, mediante el identificador input submit.    
if(isset($_POST['registrar'])){

    //Comprobamos que no haya ningun campo vacio del formulario.
    if (empty($_POST['nnombre']) && empty($_POST['napellido']) && empty($_POST['ndoc']) && empty($_POST['ndireccion']) && empty($_POST['ntelf'])) {
        //Mensaje Error.
        $msg = "Ups, todos los campos del formulario son obligatorios.";
    } else {
        //Verdadero, obtenemos datos.
        $nombre = $_POST['nnombre'] ?: '';
        $apellido = $_POST['napellido'] ?: '';  
        $tipo_doc = $_POST['ntdoc'] ?: '';
        $documento = $_POST['ndoc'] ?: '';
        $direccion = $_POST['ndireccion'] ?: '';
        $telf = $_POST['ntelf'] ?: '';
    }

    //Comprobamos que todos nuestros datos sean verdadero.
    if ($nombre && $apellido && $tipo_doc && $documento && $direccion && $telf) {

        //Requeremos conexión MySQL (¡Importante! Llamamos a nuestra conexión donde vamos a utilizarlo).
        require_once'conexion.php';

        //Sentencia preparada.
        $sql = $conn->prepare("INSERT INTO cliente (nombre,apellidos,tipo_doc,dni,direccion,telfmovil) VALUES (?,?,?,?,?,?)");      

        //Ligamos parametros marcadores (?,?,?,... es decir, $nombre,$apellido,$tipo_doc,...)

        //Especificación del tipo de caracteres:

        //i     la variable correspondiente es de tipo entero
        //d     la variable correspondiente es de tipo double
        //s     la variable correspondiente es de tipo string
        //b     la variable correspondiente es un blob y se envía en paquetes

        $sql->bind_param("ssssss",$nombre,$apellido,$tipo_doc,$documento,$direccion,$telf); 

        //Ejecutar sentencia
        $ejecutar = $sql->execute();

        //Comprobamos que se ejecutó correctamente.
        if (false===$ejecutar) { #Falso

            exit('execute() failed: ' . htmlspecialchars($sql->error));

        } else { #Verdadero.

            //Mensaje OK.
            $msg = ucfirst($nombre) . " tus datos se registraron con exito.";
        }

        //Cerrar sentencia.
        $sql->close();      

    }

}//Fin isset.

//Mensajes OK / ERRORES.
echo $msg;        

?>
    
answered by 25.12.2016 в 17:29