0

PHP

    $data = array(
        'success' => false,
        'errors' => array()
    );

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


            $inputs = $_POST['inputs'];
            foreach($inputs as $input) {

                    $name = $input['name'];
                    $value = $input['value'];

                    switch ($name) {
                            case 'email':
                                    if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                                            $msg = "You must provide a valid e-mail address";
                                    }
                                    break;

                            default:
                                    $msg = "Sorry, we do not understand the data, please try again";
                                    break;
                    }

                    if(!empty($msg)) {
                            $data['errors'][] = array(
                                    'msg' => $msg,
                                    'field' => $name
                            );
                    }
            }

            if(empty($data['errors'])) {
                    $data['success'] = true;

                    $json = file_get_contents('php://input');
                    $obj = json_decode($json,true);

                    foreach ($obj as $item) {
                            $query = "INSERT INTO users (email)

                            VALUES

                            ('".$item['email']."')";

                            $objConnection->query($query) or die($objConnection->error);
                            $objConnection->close();
                    }

            }

    } else {
            $data['errors'][] = "Data missing";
    }
    header("Content-type: application/json; charset=UTF-8");
    echo json_encode((object)$data);

Jquery / AJAX

$(function() {
    $('.submit').click(function() {

            var formInputs = new Array();

            var formId = $(this).parent().attr('id');

            $('#' + formId + ' input').each(function() {

                    var obj = {
                        'value': $(this).val(),
                        'name': $(this).attr('name')
                    };

                    formInputs.push(obj);
            });

            $.ajax({
                    url: 'add.php',
                    type: 'POST',
                    dataType: 'json',
                    cache: false,
                    data: {
                            'inputs': formInputs
                    },
                    success: function(data) {
                            if(data.success) {
                                    $(".hej").html("worked");
                            } else {
                                    $.each(data.errors, function() {
                                            var list = "<p>"+this.msg+"</p>";
                                            $(".hej").html(list);
                                    });
                            }
                    }
            });

            return false;

    });
});

I have been searching for an answer, to see if I could figure it out myself, I did find this Insert data with JSON and mysql . It seems to be working, besides that it gives me an error that says: "Invalid argument supplied for foreach()". If anyone has a better method / solution to insert the data, I am open ears.

Community
  • 1
  • 1
Simon
  • 120
  • 2
  • 10
  • You do not show any HTML stripping in this code, neither what database API you're using. Ensure you're either using PDO or stripping the content of un-trusted data before inserting it into the query (preventing SQLi injections). – Jaquarh Mar 29 '16 at 15:23
  • 1
    currently i'm just testing, security will come later – Simon Mar 29 '16 at 18:36

2 Answers2

0

Change this....

$json = file_get_contents('php://input');
$obj = json_decode($json,true);

foreach ($obj as $item) { //

To

$inputs = $_POST['inputs'];
foreach ($inputs as $item) { // rest of your code 

the reason is because you're posting, and not telling it application/json , so its using the default application/x-www-form-urlencoded

So notice when youre doing the check at the top, you use $_POST. but then the bottom section uses file_get_contents. Just use $_POST and your foreach will have values.

And judging by your switch statement at the top as well, you'll likely have to do a similar switch to insert the correct email.

Like so...

$inputs = $_POST['inputs'];
foreach($inputs as $item) {
    $name = $item['name'];
    $value = $item['value'];
    if($name=='email'){
        $query = "INSERT INTO users (email) VALUES ('".$value."')";
        $objConnection->query($query) or die($objConnection->error);
        $objConnection->close();
    }
}
Kylie
  • 11,421
  • 11
  • 47
  • 78
  • Will this work as well if I have more rows in my database? `$query = "INSERT INTO users (email, name, username) VALUES ('".$value."')"` To me it seems like this would work only work with one input field and row, not multiple. @KyleK – Simon Mar 29 '16 at 18:46
  • Well yes, you are correct in thinking there must be a better way. But what is there will work. Because you are looping, so you are inserting each value seperately. The better way would be to loop through all your inputs and build an isert, and then just do one insert at the end. – Kylie Mar 30 '16 at 15:02
0

I figured it out!

if(empty($data['errors'])) {

    $data['success'] = true;

    $inputs = $_POST['inputs'];
    $email = $inputs[0]['value']; // I select the first element in my array, then I select its value
    $password = $inputs[1]['value']; // I select the second element in my array, then I select its value

    $query = "INSERT INTO users (email, password)

    VALUES

    ('{$email}', '{$password}')";

}
Simon
  • 120
  • 2
  • 10