简体   繁体   中英

fail to create account via php on mysql database

I´m having trouble creating data onto a MySQL database via a php that I created in order to be able to create an account on a website I´m making I have the following php files that take care of the process (linked below), I have been looking to these lines of code for hours and I'm not able to figure out what is wrong with it ....

signup.php

<?php 
require 'db.php';
session_start();
?>

<!DOCTYPE html>
<html>
  <head>
    <title>AlojArt Reservas</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap -->
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <!-- styles -->
    <link href="css/styles.css" rel="stylesheet">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
    <![endif]-->
  </head>

<?php 
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
    if (isset($_POST['login'])) { //user logging in

        require 'login.php';

    }

    elseif (isset($_POST['register'])) { //user registering

        require 'register.php';

    }
}
?>

  <body class="login-bg">
    <div class="header">
        <div class="container">
            <div class="row">
                <div class="col-md-12">

                  <!-------------------- Logo -------------------->
                  <div class="logo">
                     <h1><a href="index.php">AlojArt Reservas</a></h1>
                  </div>

               </div>
            </div>
        </div>
    </div>

    <div class="page-content container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4">
                <div class="login-wrapper">
                    <div id="register">
                        <div class="box">
                            <form action="signup.php" method="post" autocomplete="off"> 
                                <div class="content-wrap">
                                    <h6>Criar conta</h6>
                                    <input class="form-control" type="text" placeholder="Nome" name="nome_titular">
                                    <input class="form-control" type="text" placeholder="Nome de utilizador " name="username">
                                    <input class="form-control" type="password" placeholder="Palavra-passe" name="password">
                                    <input class="form-control" type="email" placeholder="Endereço de e-mail" name="email">
                                    <div class="action">
                                        <button class="btn btn-primary btn-lg" name="register" />Criar conta</button>
                                    </div> 
                                </div>
                            </form>    
                        </div>
                    </div>


                    <div class="already">
                        <div id="login">
                            <p>Já tem conta?</p>
                            <a href="index.php">Iniciar sessão</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>



    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://code.jquery.com/jquery.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <script src="js/custom.js"></script>
  </body>
</html>

register.php

<?php
require 'db.php';
session_start();

$_SESSION['nome_titular'] = $_POST['nome_titular'];
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['email'] = $_POST['email'];

// Escape all $_POST variables to protect against SQL injections
$nome_titular = $mysqli->escape_string($_POST['nome_titular']);
$username = $mysqli->escape_string($_POST['username']);
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));

// Check if user with that email already exists
$result = $mysqli->query("SELECT * FROM Utilizador WHERE email='$email'") or die($mysqli->error());

// We know user email exists if the rows returned are more than 0
if ( $result->num_rows > 0 ) {

    $_SESSION['message'] = 'O utilizador jรก existe!';
    header("location: error.php");
}

else { // User doesn't already exist in a database, proceed...

    $sql = "INSERT INTO Utilizador (nome_titular, username, email, password)"
            . "VALUES ('$nome_titular','$username','$email','$password')";

    // Add user to the database
    if ( $mysqli->query($sql) ){

        $_SESSION['logged_in'] = true;
        header("location: dashboard.php");

    }

    else {
        $_SESSION['message'] = "O registo falhou!";
        header("location: error.php");
    }

}

?>

EDIT: added db.php

db.php

<?php
/* Database connection settings */
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'projeto2_dcw';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
?>

I see there is no space ' ' before VALUES , this would cause failure of SQL.

Change your SQL to

 $sql = "INSERT INTO Utilizador (nome_titular, username, email, password)"
        . " VALUES ('$nome_titular','$username','$email','$password')";

If you still getting unexpected result, then please put following code to else get the error and comment out everything else.

printf("Error: %s\n", $mysqli->error);

==Update==

"Error: Duplicate entry '0' for key 'PRIMARY"

It refers to primary key constraint violation, in other word, you are trying to insert new value 0 , which is already present in same column. Since, primary key doesn't allow duplicate. It is failing and falling to else block. To correct this issue, you need to make sure, you don't have duplicate entry for column which has primary key .

I see there is no connection for your page thats why it gets redirected to error.php change your db connection to this

<?php
$host = 'CENSORED';
$user = 'CENSORED';
$pass = 'CENSORED';
$db = 'projeto2_dcw';
$con = mysqli_connect("$host,$user,$pass,$db") or die($mysqli->error);
mysqli_select_db($con,"your db name");
?>

in the form change button <button type="submit" class="btn btn-primary btn-lg" name="register" />Criar conta

ALTER TABLE Your table name
ADD PRIMARY KEY (ID);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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