user6554670 user6554670 - 5 months ago 16
MySQL Question

Please review/comment: php mysql javascript (not school)

Many thanks to everyone. I have entered the solution Drew pointed out but am still having some issues. This could be due to mysql settings however i believe i have autocommit set properly etc. I'll post back soon.

Answer

I fixed up whatever looked wrong, not sure if I missed something.

Edit: forgot to mention, lookup password_hash and implement that. Storing password in plaintext is a no go.

Edit 2: Added the password hash function to get your started. Use password_verify to verify passwords on login.

<form onsubmit="return register(this);">
    <input name="uname" type="text" placeholder="please enter a user name"   required><br />
    <input name="upassword" type="text" placeholder="please enter a password or passphrase" required><br />
    <input id="register" name="register" type="submit" class="btn btn-primary btn-lg outline"/>
</form>

js

function register(form) {
    $.post("register.php", $(form).serialize());
    return false;
}

php

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

define('USER', 'root');
define('PASS', 'password');

try {
    $conn = new PDO("mysql:host=localhost;dbname=users;", USER, PASS);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    define('uname', $_POST['uname']);
    $passwordHash = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
    define('upassword', $passwordHash);

    $sql = 'INSERT INTO `users` (name , password) VALUES (?, ?)';
    $conn->prepare($sql)->execute([uname, upassword]);
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>