0

I'm very new to JSON, currently I have been trying to insert into a database currently I get the correct message for everything input an passing validation correctly (the validation still needs some work I know) however I can't get it to insert into a database, any advice would be great.

HTML Game of Thrones social

    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<script>
$(document).ready(function() {
    $("form").on("submit", function(event) {
            event.preventDefault();
            $("span.error").empty()
            $("span.success").empty()
            $.getJSON('registerForm.php', $(this).serialize(), function(data) {
                    if (!data.errors) {
                        $(".success").append(data.message) // deal with a no-error response ( all is good)
                    }else{
                        $.each(data.errors,function(i,datum){
                            $("[name='"+datum.name+"']").next().html(datum.error)
                        })
                    }
            });
    });
});
</script>

</head>
    <body>
    <span class="success"></span>
    <form action="" method="POST">
    <div class="formControl">
        <input type="input" name="username" placeholder="Username" value="">
        <span class="error"> </span>
    </div>
    <div class="formControl">
        <input type="text" name="email" placeholder="E-mail"  value="">
        <span class="error"></span>
    </div>
    <div class="formControl">
        <input type="password" name="password" placeholder="Password">
        <span class="error"> </span>
    </div>
    <div class="formControl">
        <input type="password" name="repeatPassword" placeholder="Confirm Password">
        <span class="error"> </span>
    </div>
    <div class="formControl">
        <input type="hidden" name="code" value="<?php echo substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1).substr(md5(time()),1); ?>">
        <span class="error"> </span>
    </div>  
    <input type="submit" value="Submit">
    </form>

    </body>
</html>

PHP

 <?php
require_once'connection.php';
    header('Content-Type: application/json');
    $errors = [];
    $username = trim($_GET['username']);
    $email = trim($_GET['email']);
    $password = trim($_GET['password']);
    $repeatPassword = trim($_GET['repeatPassword']);
    $errors = [];
    if(filter_var($username,  FILTER_VALIDATE_REGEXP,["options"=> [ "regexp" => "/.{6,25}/"]]) === FALSE){
        $errors[]= ["name"=>"username","error"=>"invalid Id (6 to 25 characters)"];
    }
    if(filter_var($email,FILTER_VALIDATE_EMAIL) === FALSE) {
        $errors[]= ["name"=>"email","error"=>"invalid Email"];
    }
    if(filter_var($password,  FILTER_VALIDATE_REGEXP,["options"=> [ "regexp" => "/.{6,25}/"]]) === FALSE){
        $errors[]= ["name"=>"password","error"=>"invalid password (6 to 25 characters)"];
    }
    if($password !== $repeatPassword){
        $errors[]= ["name"=>"repeatPassword","error"=>"passwords don't match"];
    }
    if (count($errors) === 0) {
        $salt= uniqid(mt_rand(), true);
        $options=['salt'=>$salt, 'cost'=>12];


        // everything is OK, the browser should send us to the next page
        $sql = "INSERT INTO username (username,password, eMail ,joinedDate, active, activecode) VALUES (:username, :password, :email ,NOW(), 0, :code)";
        $query = $db->prepare($sql);
        $query->execute();
        $json[] = array("username" => $username, "password" => $password, "email" => $email, "code" => $code);
    //  $json = json_encode($json);
    //  $json = file_get_contents('php://input');
        $obj = json_decode($json,true);

        echo json_encode(["message"=>"Please view your email account to activate your account"]);

    }else{
        echo json_encode(["errors"=>$errors]);
    }
?>

First attempt before deletion.

This didn't work I'm not sure why, when I attempted to use echo json_encode(["message"=>"Please view your email account to activate your account"]); within if (count($errors) === 0) {} it wasn't working.

header('Content-Type: application/json');
    $errors = [];
    $username = trim($_GET['username']);
    $email = trim($_GET['email']);
    $password = trim($_GET['password']);
    $repeatPassword = trim($_GET['repeatPassword']);
    $code = $_GET['code'];
     $query = $db->prepare("SELECT username.username FROM username WHERE username.username = :username LIMIT 1");
     $query->bindValue(':username', $username, PDO::PARAM_STR);
     $query->execute();

    if ( $query->rowCount() > 0 ) {
        $response=1;
         $errors[]= ["name"=>"username","error"=>"Username taken"];
    }

    if(filter_var($username,  FILTER_VALIDATE_REGEXP,["options"=> [ "regexp" => "/.{3,25}/"]]) === FALSE){
        $errors[]= ["name"=>"username","error"=>"invalid Id (3 to 25 characters)"];
    }
    if(preg_match('/[^a-z_\-0-9]/i', $username))
        {
            $errors[]= ["name"=>"username","error"=>"invalid Id (Usernames may not contain symbols)"];
        }

    if(filter_var($email,FILTER_VALIDATE_EMAIL) === FALSE) {
        $errors[]= ["name"=>"email","error"=>"invalid Email"];
    }

    $emailQ = $db->prepare("SELECT username.eMail FROM username WHERE username.eMail = :email LIMIT 1");
     $emailQ->bindValue(':email', $email, PDO::PARAM_STR);
     $emailQ->execute();

    if ( $query->rowCount() > 0 ) {
        $response=1;
         $errors[]= ["name"=>"email","error"=>"Email registered"];
    }


    if(filter_var($password,  FILTER_VALIDATE_REGEXP,["options"=> [ "regexp" => "/.{6,25}/"]]) === FALSE){
        $errors[]= ["name"=>"password","error"=>"invalid password (6 to 25 characters)"];
    }

    if(!preg_match("/(?=[a-z]*[0-9])(?=[0-9]*[a-z])([a-z0-9-]+)/i",$password)) {
         $errors[]= ["name"=>"password","error"=>"Password must contain numbers and letters"];
    }

    if($password !== $repeatPassword){
        $errors[]= ["name"=>"repeatPassword","error"=>"passwords don't match"];
    }


$salt= uniqid(mt_rand(), true);
$options=['salt'=>$salt, 'cost'=>12];

    if (count($errors) === 0) {
        // everything is OK, the browser should send us to the next page

        $sql = "INSERT INTO username (username,password, eMail ,joinedDate, active, activecode) VALUES (:username, :password, :email ,NOW(), 0, :code)";
        $query = $db->prepare($sql);

        $query->execute(array(
            ':username'=> $username,
            ':password'=> $cryptpwd=crypt($password,'$2y$12$'.$salt.'$'),
            ':email'=> $email,
            ':code'=> $code
        ));


    echo $message = '
    http://gotsocial.co.uk/active.php?activecode='.$code.'.
    ';
    $to = $email;
    $subject = 'Game of Thrones Social';
    $from = "register@gotsocial.co.uk";

    $result = mail($to, $subject, $message, "From: $from");

     echo json_encode(["message"=>"Please view your email account to activate your account"]);

    }
    echo json_encode($errors);

This section here is my problem, without it my success message will show up with it my success message will not show up.

echo $message = '
    http://gotsocial.co.uk/active.php?activecode='.$code.'.
    ';
    $to = $email;
    $subject = 'Game of Thrones Social';
    $from = "register@gotsocial.co.uk";

    $result = mail($to, $subject, $message, "From: $from");
sam thenoob
  • 99
  • 1
  • 9
  • Do you get an errors on the db side? – LearningPhase Apr 20 '16 at 19:18
  • You never execute your query – Mihai Apr 20 '16 at 19:19
  • I updated with my most recent attempt – sam thenoob Apr 20 '16 at 19:25
  • What's happening here is you're slowly working your way through your errors, the latest one is because an attempt to send an email is failing, but the error messages are hidden. The proper thing to do is to find out where those errors are going, probably to a web server error log, and read them. Otherwise you're stumbling around in the dark. The answers to [How to get useful error messages in PHP?](https://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php) will help. – Schwern Apr 20 '16 at 21:57
  • Thanks, currently trying ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); with display_errors = on Those two pieces of code are causing the problem but I really can't see any error messages other wise I'd be able to search for something – sam thenoob Apr 20 '16 at 22:42
  • Solution was to remove echo... – sam thenoob Apr 20 '16 at 23:48

1 Answers1

0

JSON is not involved here. The problem is you're using SQL bind parameters (this is good) but not passing in any values when you execute it.

    $sql = "INSERT INTO username (username,password, eMail ,joinedDate, active, activecode) VALUES (:username, :password, :email ,NOW(), 0, :code)";
    $query = $db->prepare($sql);
    $query->execute();

That last $query->execute(); is the problem. Execute needs a key/value pair for each of :username, :password, etc... else it will insert NULL. For this, use a normal PHP array.

$query->execute(array(
    ':username' => $username,
    ':password' => $password,
    ':email'    => $email,
    ':code'     => $code
));

If you got no error from $query->execute() this indicates that your database schema is allowing NULL values in each of those fields. You probably don't want that, as you discovered it hides mistakes. You should probably change your schema and add NOT NULL to each of those fields and remove any defaults.

Schwern
  • 153,029
  • 25
  • 195
  • 336
  • Oh I thought it'd have to be done completely in JSON, I'd done something similar to this but deleted all of to start again, will I edit that attempt in to show you – sam thenoob Apr 20 '16 at 19:51