-2

I want to insert user to my database but I get error message in my browser page. I open mysql workbench and server is online. Is there anything wrong in my code?

php

$conn = mysql_connect( "localhost", "root", "123456");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

    $dbselect = mysql_select_db("inputdatabase");
    $username = $_POST['username'];
    $password = $_POST['password'];

    $sql = "INSERT INTO studenttable (nickname, password) VALUES ('$username', '$password')";
    $loginpage = 'C:/website/loginPage.html';
    $index = 'C:/website/index.hmtl';
    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
        header( "Location: $index" );
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
        header( "Location: $loginpage" );
    }

$conn->close();
}
?>

html

      <form action="insertUser.php" method="post">    
          <div class="containerLogin">
            <label><b>Username</b></label>
            <input type="text" placeholder="Enter Username" name="username" required>
            <label><b>Password</b></label>
            <input type="password" placeholder="Enter Password" name="password" required>
                <button type="submit">Login</button>
            <input type="checkbox" checked="checked"> Remember me
          </div>
          <div class="containerLogin" style="background-color:#f1f1f1">
            <button type="buttonLogin" class="cancelbtn">Cancel</button>
            <span class="password">Forgot <a href="#">password?</a></span>
          </div>
        </form>
ozan
  • 33
  • 1
  • 9
  • 5
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Nov 09 '17 at 21:30
  • 4
    **Never** store plain text passwords. Instead use [`password_hash()`](http://us3.php.net/manual/en/function.password-hash.php) and [`password_verify()`](http://us3.php.net/manual/en/function.password-verify.php). If you're using a version of PHP prior to 5.5, do **not** use MD5 or SHA1 to hash passwords. Instead you can use [this compatibility pack](https://github.com/ircmaxell/password_compat). – Alex Howansky Nov 09 '17 at 21:31
  • 2
    Don't use the `mysql_*` functions. They have been deprecated since v5.5 (Jun 2013) and removed since v7.0 (Dec 2015). Instead use the [**mysqli_***](https://secure.php.net/manual/en/book.mysqli.php) or [**PDO**](https://secure.php.net/manual/en/book.pdo.php) functions with [**prepared statements**](https://secure.php.net/manual/en/pdo.prepare.php) and [**bound parameters**](https://secure.php.net/manual/en/pdostatement.bindparam.php). – Alex Howansky Nov 09 '17 at 21:31
  • 2
    What error do you get? What version of PHP are you on? `mysql_select_db` was removed in PHP7 – dave Nov 09 '17 at 21:31
  • 2
    Deploying this code is an egregious and unforgivable security risk. Please read [OWASP](https://www.owasp.org/index.php/Main_Page) before continuing with your project. – Guillaume CR Nov 09 '17 at 21:36
  • I cannot use this php code. If I can add some user to my database, I will protect my code from SQL injection and I will pash my password. – ozan Nov 09 '17 at 21:46
  • what error are you getting?you didnt specify – Alexander Omoruyi Nov 09 '17 at 21:48
  • In chrome console I do not get any error. In web page only written(Cannot POST /insertUser.php), it does not locate any html page. However, I cannot add anything to my database. – ozan Nov 09 '17 at 22:03
  • I cannot find my php version. Maybe php did not installed with mysql workbench 6.3 which I'm using now. – ozan Nov 10 '17 at 00:19

1 Answers1

0

OK. So from reading your code it appears you are quite new to PHP (I might be wrong). I will plead with you to follow this advice:

  1. You have to take time to research and understand how to avoid some of the fundamental security loopholes and pitfalls when coding with PHP. eg. proper handling of passwords.
  2. Be consistent with the style you choose. If you are going with procedural stick with it, if you are going with object oriented stick with it. From your code you appear to be mixing the two. It might work but consistency always pays. Plus you should be aiming at learning object oriented and ultimately switch to PDO.
  3. Please at all cost never ever use anymysql_* type function. Use mysqli_* instead; the i stands for improved. mysql was deprecated in PHP v5.5 and in v7.0 it has been removed.

All right so now let's try to solve the problem at hand.
(I'm presuming you have PHP 5 or later)
For the sake of brevity, I'm not including validation and sanitization of the user input

PHP

if (isset($_POST['submit'])) { // <- Code will run only when the submit button is clicked

    // Here the database is included. No need for mysqli_select_db
    $conn = new mysqli('localhost', 'root', '12345', 'inputdatabase');

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT); // Encrypt the password)

    // Its always good to prepare your sql statements.
    $prep = $conn->prepare("INSERT INTO studenttable (nickname, password) VALUES (?,?)");

    // Bind parameters
    $prep->bind_param("ss", $username, $password);   

    // Execute the prepared sql statement. This line can even be avoided though
    $send = $prep->execute();    

    // Check if the execution was successful
    // Again this check can even be simplified to: if ($send) {...do something;}
    if ($send === TRUE) {
        echo "New record created successfully";    //<-- You won't get to see this because of the next line.
        header("Location: $index");
        exit();
    } else {
        echo "Error: " . $conn->error;
        header("Location: $loginpage");
        exit();
    }

   $prep->close();
    $conn->close();
}

HTML

Just use <input> tags for your html form buttons instead of the <button> tag

<form action="" method="post">
    <div class="containerLogin">
        <label><b>Username</b></label>
        <input type="text" placeholder="Enter Username" name="username" required>
        <br>

        <label><b>Password</b></label>
        <input type="password" placeholder="Enter Password" name="password" required>
        <br>
        <br>

        <input type="checkbox" checked="checked">Remember Me
        <br>
        <br>
    </div>

    <div class="containerLogin" style="background-color:#f1f1f1">

    <!-- Use <input type='submit'> for your form buttons. Instead of <button> -->
        <input type="submit" name="submit" value="Login">
        <input type="reset" class="cancelbtn" value="Cancel">
        <br>
        <span class="password">Forgot <a href="#">password?</a></span>
    </div>
</form>

This code is relatively better. But I must say that it can even get better optimized and enhanced. User inputs must be validated, you should keep your database credentials hidden in a different file and included here etc..

I hope this helps. Try this let's see. Corrections are welcome.

Nana Yeboah
  • 1
  • 1
  • 2
  • I'm new to PHP and thank you for your help. I change button to input and mysql to mysqli and other things what you said. It is not working but I improve my code, I think. Maybe I should change mysql workbench 6.3 instead of wamp? – ozan Nov 10 '17 at 11:08
  • Yes, Wamp server can be helpful. It comes with phpmyadmin which can make usage of MySQL very easy. Feel free to get in touch. I am always willing to help. We can correspond more to help you get going. Do you know how to use a tool called git? With git I can get access to your code and help you correct it. You must also pay attention to the action of your html form. If the PHP is in a different file from the html, then make sure you write the path to the file correctly. – Nana Yeboah Nov 10 '17 at 11:16