BugDroid777
BugDroid777

Reputation: 67

HTML Form and PHP Script to insert into database not working

I am trying to insert a new user into my database but the php always fails, the issets im doing always return false so it doesnt insert, i have no ideia why, i bet its a basic thing to fix, im a bit frustated..

HTML PAGE

 <html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="./css/bootstrap.min.css" >
    <link rel="stylesheet" href="./css/orlando.css" >
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content=" Pagina Inicial ">

</head>

<body>

<div id="wrapper">
    <!-- Sidebar -->
    <nav class="navbar navbar-inverse navbar-fixed-top" id="sidebar-wrapper" role="navigation">
        <ul class="nav sidebar-nav">
            <li class="sidebar-brand">
                <a href="#">
                   <img src="./img/logo2.png" alt="">
                </a>
            </li>
            <li>
                <a href="index.html">Login</a>
            </li>
            <li>
                <a href="register.html">Register</a>
            </li>
            <li>
                <a href="about.html">About</a>
            </li>
            <li>
                <a href="profile.html">Profile</a>
            </li>
            <li>
                <a href="matchhistory.html">Match History</a>
            </li>
            <li>
                <a href="leaderboard.html">Leaderboard</a>
            </li>
            <li>
                <a href="contacts.html">Contacts</a>
            </li>
            <li>
                <a href="#">Logout</a>
            </li>
        </ul>
    </nav>
    <!-- /#sidebar-wrapper -->

    <!-- Page Content -->
    <div id="page-content-wrapper">
          <nav class="navbar navbar-default navbar-static-top">

            <div class="container" style="width: 100%;">
              <button type="button" class="hamburger is-closed" data-toggle="offcanvas">
                  <span class="hamb-top"></span>
            <span class="hamb-middle"></span>
          <span class="hamb-bottom"></span>
              </button>
              <div class="navbar-header">
                  <a class="navbar-brand" href="./index.html"target="_self" style="margin-left: 55px;"> <img src="./img/logo.png" alt=""></a>
             </div>
            </div>
          </nav>

          <form class="form-signin" action="register.php">
            <h2 class="form-signin-heading">Register</h2>
            <input type="text" class="form-control" name="name" placeholder="name" required="" autofocus="" />
            <input type="text" class="form-control" name="nickname" placeholder="nickname" required="" autofocus="" />
            <input type="text" class="form-control" name="email" placeholder="email" required="" autofocus="" />
            <input type="password" class="form-control" name="password" placeholder="password" required=""/>
            <label class="checkbox">
              <input type="checkbox" value="remember-me" id="rememberMe" name="rememberMe"> Remember me
            </label>
            <button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
          </form>

    <!-- /#page-content-wrapper -->
  </div>
</div>

<!-- /#wrapper -->

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="./js/bootstrap.min.js"></script>
        <script src="./js/master.js"></script>
</html>

PHP SCRIPT:

   <?php

define("DB_HOST", "");
define("DB_USER", "");
define("DB_PASSWORD", "");
define("DB_DATABASE", "");

$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE) or die('Oops');
//verificar se a ligação foi feita com sucesso
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if (isset($_POST['name']) && isset($_POST['nickname']) && isset($_POST['email']) && isset($_POST['password'])) {

  echo "isset";
  $name = $_POST['name'];
  $nickname = $_POST['nickname'];
  $email = $_POST['email'];
  $password = $_POST['password'];

  $query = "INSERT INTO users(name, nickname, email, password) VALUES ('$name', '$nickname', '$email', '$password' )";
  $insert = mysqli_query($con, $query) or die ('Error');

  if ($insert) {
        echo "sucess";
     } else {
        echo "RIP";
     }
  } else {
    echo "error";
  }

?>

It echos the "error".

Thanks.

Upvotes: 1

Views: 1203

Answers (4)

Meir
Meir

Reputation: 61

this is not the only problem that you have with your script.

First of all you should try to work with classes and use PDO so if you would have to change Database your script could be very easy to update to new database, it add flexibility to your script. The PHP Data Objects (PDO) extension

Second you should never insert to your SQL statment data that you got from the user before prosesing it, othervise you voranble to sql injection. You could do it very easy with PDO:: prepare

PDO::prepare

I prefer to use this code, it's much more cleaner and easy to manage :

if("POST" == $_SERVER['request_method']){
    
}

and not to use your very long line:

if (isset($_POST['name']) && isset($_POST['nickname']) && isset($_POST['email']) && isset($_POST['password'])) {

and about your problem that You get a error, you forgot to put to your form

method="POST"

Upvotes: 0

defo
defo

Reputation: 7

You need to use try{}catch{} in order to avoid password leak in case of errors.

  class bd{  
                static function connexion(){
                    try{
                       //LOCAL
                        $dsn = "mysql:host=localhost;dbname=name";
                        $usr = "username";
                        $pass = "password";

                        $options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
                        $bdd = new PDO($dsn, $usr, $pass);
                        $bdd->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
                        $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                        return $bdd;
                    }catch(Exception $e){
                        echo $e->getMessage();
                    }
                }


            static function execQuery($bdd, $query){
                try{
                    $req = $bdd->prepare($query);
                    $req->execute();
                    $result = $req->fetchAll(PDO::FETCH_ASSOC);
                    $req->closeCursor();
                    return $result;
                } catch( PDOEXception $e ) {
                       echo $e->getMessage(); // display bdd error
                       exit();
                   }
               }
            }

      $name = $_POST['name'];
      $nickname = $_POST['nickname'];
      $email = $_POST['email'];
      $password = $_POST['password'];
      $bdd = bd::connexion();
      $req = $bdd->prepare("INSERT INTO users(name, nickname, email, password) VALUES ('$name', '$nickname', '$email', 

'$password' );");

Upvotes: 0

Logan Wayne
Logan Wayne

Reputation: 5991

  • The error text message you are getting means that it is not reading the isset() condition.

You can try to replace and do a single condition instead by putting first a name attribute on your button:

<button class="btn btn-lg btn-primary btn-block" name="register" type="submit">Register</button>

Then the condition:

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

So you can use a back-tick (`) to encapsulate those column names:

$query = "INSERT INTO users(`name`, `nickname`, `email`, `password`) VALUES ('$name', '$nickname', '$email', '$password' )";
  • You might also want to check prepared statement since you are using mysqli_* API already, so you don't have to bind raw data into your queries.
  • I missed this, but you forgot method="POST" attribute on your <form> tag

Upvotes: 0

BizzyBob
BizzyBob

Reputation: 14740

You need to add method="post" to your form..!

The reason all your conditions are failing is because $_POST is null. You aren't posting any data since the default form method is GET.

Upvotes: 2

Related Questions