0

i am using php and mysql db , i want take the values from the two input type and insert them to data base when the button save clicked when run the code no erros shown but its do not save in the db here is the code. (note that the id is auto increment and the admin table contains three columns id,username , password) addAdmin.php :

<?php include("connect.php");?>
<div class="col-md-12">
<!-- Add admin -->
<div class="box box-info">
  <div class="box-header with-border">
    <h3 class="box-title">Add admin</h3>
  </div>
  <!-- /.box-header -->
  <!-- form start -->
  <form id="adminForm" class="form-horizontal" action="" method = "get">
    <div class="box-body">

        <div class="form-group">
        <label for="inputName" class="col-sm-2 control-label">User 
  name</label>

        <div class="col-sm-10">
          <input type="text" class="form-control" id="inputName" 
           placeholder="user name" name="username" required >
        </div>
      </div>

      <div class="form-group">
        <label for="inputPassword3" class="col-sm-2 control-
  label">Password</label>

        <div class="col-sm-10">
          <input type="password" class="form-control" id="inputPassword3" 
  placeholder="Password" name="password" required>
        </div>

      </div>





    </div>
    <!-- /.box-body -->
    <div class="box-footer">
        <input  type = "submit" class="btn btn-info pull-right save" name = 
     "submit" value = "save">
      <?php 
      if(isset($_POST["submit"])) {
          $name = $_GET['username'];
          $password = $_GET['password'];


          $insertNewAdmin = "INSERT INTO `admin` VALUES 
          ('$name','$password')";
          mysql_query($insertNewAdmin);

      }
      ?>
    </div>
    <!-- /.box-footer -->
  </form>
</div>
<!-- /.box -->
</div>
  • 3
    You need to stop using `mysql_*` functions. They have been deprecated for years and don't even exist in current PHP releases. I suggest studying about [PHP Data Objects](http://php.net/manual/en/book.pdo.php), known as PDO for short, for a more modern approach. – sidyll May 26 '17 at 14:44
  • 2
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard May 26 '17 at 14:45
  • 2
    **Never store plain text passwords!** Please use ***PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html)*** to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). ***It is not necessary to [escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard May 26 '17 at 14:45
  • 1
    Do you only have 2 columns in your database? If not you'll have to use the longer version of an INSERT statement where you specify the columns. Even though no errors show on your web page there might be errors in the error logs of your web server. – Jay Blanchard May 26 '17 at 14:47
  • @JayBlanchard the poor guy is probably just trying to work through an old legacy site, he needs help and now its his fault the code sucks lol – Flosculus May 26 '17 at 14:51
  • Perhaps @Flosculus, but he hasn't given us any detail to be able to solve his problem. The only thing I can see which might be problematic is the INSERT statement, but the OP has not answered my question about the columns...the likely culprit. – Jay Blanchard May 26 '17 at 14:55
  • OP probably ran away now lol. – Rotimi May 26 '17 at 14:55
  • 1
    I see another big issue. OP also set the form method to `get` and is checking for a `POST` – Rotimi May 26 '17 at 14:58
  • we're blinded by the obvious, omg ... – Flosculus May 26 '17 at 15:04

1 Answers1

3

Allow me to re write your full code for you using the recommended industry standards. First of all you should never ever use the get method $_GET when sending a form data to a database more especially when it contains passwords.

mysql_* api that you are using has been depreciated since I was doing my second year at college, I have graduated and with 3 years working experience, since it was depreciated ;) and was completely remove on php 7.. therefore you should be using mysqli_* or PDO as of v5.5.0 see : Why shouldn't I use mysql_* functions in PHP?

then another issue with your code is at risk of sql inections as @Jay Blanchard have stated above, you can follow his block here to learn more about what he' saying : http://jayblanchard.net/demystifying_php_pdo.html

so to solve what Jay have highlighted above we use something called prepared statements : which prevents against SQL injections.

Then we also in the modern days do not store passwords in plain texts or md5 these days we use password_hash() and password_verify() to store password hash in the database and check the stored password against the user entered password:

in my code you will see : (userNameColumnName,passwordColumnName) userNameColumnName is the column in your table where you will store username and passwordColumnName is teh column in your table where you will store password and make sure the char length is at least 60 chars or better 255.

You can't insert values like this "INSERT INTOadminVALUES ('$name','$password') unless you have exactly two fields in your tabl e as I guess you don't you should atleast have 3. connect.php

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

then the other page

<?php include("connect.php");

    $errors=false;

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

    $fields = array("username","password");
    foreach($fields as $fieldname){
        if(!isset($_POST[$fieldname]) && empty($_POST[$fieldname])){

            echo "enter username and password";
            $errors = true;
        }
    }

    if(!$errors){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $hash = password_hash($password);

        $sql = "INSERT INTO admin (userNameColumnName,passwordColumnName) VALUES(?,?)";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ss",$username,$hash);
        if($stmt->execute()){

            echo "user added";
        }else{

            echo "error adding user";
            error_log("error".$conn->error); // go and check your error log what was the error
        }
    }

}

?>
<div class="col-md-12">
    <!-- Add admin -->
    <div class="box box-info">
        <div class="box-header with-border">
            <h3 class="box-title">Add admin</h3>
        </div>
        <!-- /.box-header -->
        <!-- form start -->
        <form id="adminForm" class="form-horizontal" action="" method = "POST">
            <div class="box-body">
                <div class="form-group">
                    <label for="inputName" class="col-sm-2 control-label">User 
                    name</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="inputName" 
                            placeholder="user name" name="username" required >
                    </div>
                </div>
                <div class="form-group">
                    <label for="inputPassword3" class="col-sm-2 control-
                        label">Password</label>
                    <div class="col-sm-10">
                        <input type="password" class="form-control" id="inputPassword3" 
                            placeholder="Password" name="password" required>
                    </div>
                </div>
            </div>
            <!-- /.box-body -->
            <div class="box-footer">
                <input  type = "submit" class="btn btn-info pull-right save" name = "submit" value = "save">
            </div>
            <!-- /.box-footer -->
        </form>
    </div>
    <!-- /.box -->
</div>
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34
  • OP is a beginner. might not understand this `$sql = "INSERT INTO admin (userNameColumnName,passwordColumnName) VALUES(?,?)";` OP might even copy the whole thing and paste. ALthough your answer is perfect `+1` – Rotimi May 26 '17 at 15:00
  • @Akintunde thanks, I'm writing the explanations as we speak – Masivuye Cokile May 26 '17 at 15:01
  • Awesome. Please do – Rotimi May 26 '17 at 15:01
  • 1
    @Akintunde I have updated please see, if it all makes sense – Masivuye Cokile May 26 '17 at 15:30
  • @MasivuyeCokile thank you for the great answer , but may be i am doing something wrong when using your code , it is did not work , the admin table contains three columns (id_admin , user_name , password), and the id_admin is auto increment , i use the insert statment like this $sql = "INSERT INTO admin (user_name,password) VALUES('$username','$password')"; – Mahmood Mousa May 26 '17 at 16:40
  • Makes sense. Perfect! – Rotimi May 27 '17 at 10:23
  • Maybe you can also add how OP can verify the password on login – Rotimi May 27 '17 at 10:24