0

I have this login, access to the database. the problem I have is that it does not insert the fields that I pass through the post.

I attach my codes to the php that sends the information to the database. El js en los mensajes de error i el index.php

Php send the post in the BD the name is create.php.

<?php
session_start();

include_once 'conexion.php';
$objeto = new Conexion();
$conexion = $objeto->Conectar();

//recepción de datos enviados mediante POST desde ajax
$usuario = (isset($_POST['usuario'])) ? $_POST['usuario'] : '';
$email = (isset($_POST['email'])) ? $_POST['email'] : '';
$password = (isset($_POST['password'])) ? $_POST['password'] : '';
$cpassword = (isset($_POST['cpassword'])) ? $_POST['cpassword'] : '';

$pass = md5($password); //encripto la clave enviada por el usuario para compararla con la clava 
encriptada y almacenada en la BD

$consulta =  "SELECT * FROM usuarios WHERE email = '$email'";
    if(mysqli_num_rows($consulta)) {
        echo 'This email already exists';
    }

    else {
        $resultado = $conexion->prepare($consulta);
        $resultado->execute();

        if($resultado->rowCount() >= 1){
            $data = $resultado->fetchAll(PDO::FETCH_ASSOC);
            $query    = "INSERT into `usuarios` (usuario,  email, password)
            VALUES ('$usuario', '$email', '$pass')";
        }else{
            $_SESSION["s_usuario"] = null;
            $data=null;
        }
        
    }


 print json_encode($data);
 $conexion=null;

The .js contains form error messages

$('#formLogin').submit(function(e){
e.preventDefault();
var usuario = $.trim($("#usuario").val());    
var password =$.trim($("#password").val());    

if(usuario.length == "" || password == ""){
  Swal.fire({
      type:'warning',
      title:'Debe ingresar un usuario y/o password',
  });
  return false; 
}else if{
    $.ajax({
       url:"bd/login.php",
       type:"POST",
       datatype: "json",
       data: {usuario:usuario, password:password}, 
       success:function(data){               
           if(data == "null"){
               Swal.fire({
                   type:'error',
                   title:'Usuario y/o password incorrecta',
               });
           }else{
               Swal.fire({
                   type:'success',
                   title:'¡Conexión exitosa!',
                   confirmButtonColor:'#3085d6',
                   confirmButtonText:'Ingresar'
               }).then((result) => {
                   if(result.value){
                       window.location.href = "dashboard/index.php";
                   }
               })
               
           }
       }    
    });
}     
else{
    $.ajax({
       url:"bd/registrar.php",
       type:"POST",
       datatype: "json",
       data: {usuario:usuario, password:password}, 
       success:function(data){               
           if(data == "null"){
               Swal.fire({
                   type:'error',
                   title:'Error para crear el Usuario',
               });
           }else{
               Swal.fire({
                   type:'success',
                   title:'¡Conexión exitosa!',
                   confirmButtonColor:'#3085d6',
                   confirmButtonText:'Ingresar'
               }).then((result) => {
                   if(result.value){
                       window.location.href = "index.php";
                   }
               })
               
           }
       }    
    });
  } 
 });

Index.php

<html>
<head>
    <title>Rem la Ràpita - Sign In</title>
    <link rel="icon" type="image/png" href="../images/favicon.png" sizes="52x52"/>
    
    <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="estilos.css">
    <link rel="stylesheet" href="plugins/sweetalert2/sweetalert2.min.css">        
    <link rel="stylesheet" type="text/css" href="fuentes/iconic/css/material-design-iconic-font.min.css">
</head>
<body>
  <div class="container-login">
    <div class="wrap-login">
        <form class="login-form validate-form" id="formLogin" action="bd/create.php" method="post">
            <span class="login-form-title">Sign In</span>
            
            <div class="wrap-input100" data-validate = "Usuario incorrecto">
                <input class="input100" type="text" id="usuario" placeholder="Nom">
                <span class="focus-efecto"></span>
            </div>
            
            <div class="wrap-input100" data-validate = "Usuario incorrecto">
                <input class="input100" type="text" id="email" placeholder="Email">
                <span class="focus-efecto"></span>
            </div>
            
            <div class="wrap-input100" data-validate="Password incorrecto">
                <input class="input100" type="password" id="password" placeholder="Contrasenya">
                <span class="focus-efecto"></span>
            </div>
            
            <div class="wrap-input100" data-validate="Password incorrecto">
                <input class="input100" type="password" id="cpassword" placeholder="Confirma Contrasenya">
                <span class="focus-efecto"></span>
            </div>
            
            <div class="container-login-form-btn">
                <div class="wrap-login-form-btn">
                    <div class="login-form-bgbtn"></div>
                    <button type="submit" name="submit" class="login-form-btn">CREAR USUARI</button>
                </div>
            </div>
        </form>
    </div>
</div>     
    
     <script src="jquery/jquery-3.3.1.min.js"></script>    
     <script src="bootstrap/js/bootstrap.min.js"></script>    
     <script src="popper/popper.min.js"></script>    
     <script src="plugins/sweetalert2/sweetalert2.all.min.js"></script>    
     <script src="codigo_registro.js"></script>    
</body>

Attached image of the database structure.

enter image description here.

Attached image of the error.

enter image description here

brombeer
  • 8,716
  • 5
  • 21
  • 27
Joel
  • 7
  • 3
  • 1
    Unrelated: from PHP's [md5](https://www.php.net/manual/en/function.md5.php) manual: "_Warning It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the [Password Hashing FAQ](https://www.php.net/manual/en/faq.passwords.php#faq.passwords.fasthash) for details and best practices._" – brombeer May 02 '22 at 07:13
  • 1
    The data you are sending is just `{usuario:usuario, password:password}`, so where do you expect `$_POST['email']` to come from now? – CBroe May 02 '22 at 07:13
  • `}else if{` - else if without any condition, does not make sense. This should be giving you script parse errors already. – CBroe May 02 '22 at 07:15
  • `$query = "INSERT into \`usuarios\` ...` where do you execute this query? – brombeer May 02 '22 at 07:16
  • As for your error image, the message is quite self-explaining: `$consulta` is a `string` - once again you need to execute that query first to get affected rows – brombeer May 02 '22 at 07:25
  • Hi, could you help me to configure the code? Thank you very much. – Joel May 02 '22 at 07:30
  • **Warning!** You're open to [SQL injection attacks](https://owasp.org/www-community/attacks/SQL_Injection)! Read [how to prevent SQL injection in PHP](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) by using prepared statements with bound parameters instead of injecting variables directly into your queries. It's not just about security. If your data contains, for example, a single quote `'`, your query will break. – M. Eriksson May 02 '22 at 07:43
  • I would recommend that you take a step back and do one thing at the time. First submit the form and check that you get all the data in PHP as expected. When that's done, continue with the first query and when that's done, continue to the next. Right now, you have issues in all steps, making the debugging harder for you. – M. Eriksson May 02 '22 at 07:46

1 Answers1

0

<html>
    <head>
        <title>Rem la Ràpita - Sign In</title>
        <link rel="icon" type="image/png" href="../images/favicon.png" sizes="52x52"/>
        
        <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
        <link rel="stylesheet" href="estilos.css">
        <link rel="stylesheet" href="plugins/sweetalert2/sweetalert2.min.css">        
        <link rel="stylesheet" type="text/css" href="fuentes/iconic/css/material-design-iconic-font.min.css">
    </head>
    <body>
    <?php
        require('dbconnect.php');
        // When form submitted, insert values into the database.
        if (isset($_REQUEST['username'])) {
            // removes backslashes
            $username = stripslashes($_REQUEST['username']);
            //escapes special characters in a string
            $username = mysqli_real_escape_string($con, $username);
            $email    = stripslashes($_REQUEST['email']);
            $email    = mysqli_real_escape_string($con, $email);
            $password = stripslashes($_REQUEST['password']);
            $password = mysqli_real_escape_string($con, $password);
            $query    = "INSERT into `usuaris` (username, password, email)
                         VALUES ('$username', '" . md5($password) . "', '$email')";

            $select_email = mysqli_query($con, "SELECT * FROM usuaris WHERE email = '".$_POST['email']."'");
            if(mysqli_num_rows($select_email)) {
                echo 'This email already exists';
            }
            //Comprovar si les contrasenyes coincideixen
            else if ($_POST["password"] === $_POST["cpassword"]) {
                $result   = mysqli_query($con, $query);
                if ($result) {
                    echo "You are registered successfully.";
                } else {
                    echo "Click here to ";
                }
            }
            else {
               echo "Les Contrasenyes no coincideixen";
            }

        } else {}
    ?>
      <div class="container-login">
        <div class="wrap-login">
            <form class="login-form validate-form"  method="post">
                <span class="login-form-title">Sign In</span>
                
                <div class="wrap-input100" data-validate = "Usuario incorrecto">
                    <input class="input100" type="text" name="username" placeholder="Nom" required="required">
                    <span class="focus-efecto"></span>
                </div>
                
                <div class="wrap-input100" data-validate = "Usuario incorrecto">
                    <input class="input100" type="text" name="email" placeholder="Email" required="required">
                    <span class="focus-efecto"></span>
                </div>
                
                <div class="wrap-input100" data-validate="Password incorrecto">
                    <input class="input100" type="password" name="password" placeholder="Contrasenya" required="required">
                    <span class="focus-efecto"></span>
                </div>
                
                <div class="wrap-input100" data-validate="Password incorrecto">
                    <input class="input100" type="password" name="cpassword" placeholder="Confirma Contrasenya" required="required">
                    <span class="focus-efecto"></span>
                </div>
                
                <div class="container-login-form-btn">
                    <div class="wrap-login-form-btn">
                        <div class="login-form-bgbtn"></div>
                        <button type="submit" class="login-form-btn">CREAR USUARI</button>
                    </div>
                </div>
            </form>
        </div>
    </div>     
        
     <script src="jquery/jquery-3.3.1.min.js"></script>    
     <script src="bootstrap/js/bootstrap.min.js"></script>    
     <script src="popper/popper.min.js"></script>    
     <script src="plugins/sweetalert2/sweetalert2.all.min.js"></script>    
     <script src="codigo_registro.js"></script>    
    </body>
</html>

I have modified the code and now I get the following errors. enter image description here

Joel
  • 7
  • 3
  • You should prefer prepared statement rather than escaping data by yourself. Otherwise, great answer ! – Xiidref May 03 '22 at 14:16