0

I have multiple input fields where a user can fill in answers to the question, with JavaScript i put the user input into a array.

When I view the console log inside google chrome I see the array wil be made correct, after that I want to sent the array with AJAX to a another php page so that i can save the data into my database.

When i check my database the post result = "Array" :(

someone who can help me???

////// JavaScript and AJAX code :

if (isConfirm) {
    checkAnswers();
    $('input[id="answer"]').each(function() {
        allAnswers.push($(this).val());
        allAnswers.toString(); 
    });
    console.log(allAnswers);
    $.ajax({
        type: 'post',
        url: 'actions/save_questions.php',
        data: { 'answers': allAnswers }
    });
}

/////// PHP code :

<?php

$user_answer = $_POST['answers'];
$date = date('d-m-Y h:i:s');

$arr = array($user_answer);

$query = "INSERT INTO made_questions (lesson_id, user_answer, datum) VALUES ('1', '$arr', '$date')";
mysqli_query($conn,$query) or die (mysqli_error($conn));

?>

The output into my database is:

id: 27

lesson_id: 1

user_answer: Array <----- this is wrong :(

datum: 16-06-2016 08:12:32

Console log output:

["horse", "nocleu", "Geel", "This is my dog", "Guten tag", "Sun", "Aap", "Honger", "knol", "Cat"]

Someone who maybe can help me???

Thanks a lot!

mferly
  • 1,646
  • 1
  • 13
  • 19
Xxx red
  • 45
  • 1
  • 2
  • 11
  • One option would be to serialize you array http://stackoverflow.com/a/1256006/4178487 – Jason K Jun 16 '16 at 18:35
  • `$foo = array(); echo $foo` will output the literal word `Array`. You cannot use an array in a string context, which includes stuffing that array into an sql query string, and mysql doesn't do arrays anyways. you need to normalize your data structure and insert each array component into a child table. – Marc B Jun 16 '16 at 18:36
  • 1
    Instead of `allAnswers.toString(); `, use `allAnswers = allAnswers.join();` – Hackerman Jun 16 '16 at 18:42
  • Agreed, @MarcB The OP is going for a comma separated list of values to put into a column in the DB. Depending on the use case, it most likely should be normalized out into a child table – mhodges Jun 16 '16 at 18:43
  • @Hackerman .join() does not modify the original variable either.. – mhodges Jun 16 '16 at 18:43
  • 1
    @mhodges, you are right, i'm editing my comment right now :) – Hackerman Jun 16 '16 at 18:46

3 Answers3

2

.toString() and .join() do not modify the original variable. You need to either say:

allAnswers = allAnswers.toString();

OR

data: {'answers': allAnswers.toString()}

Additionally

If you want the values ", " separated rather than just "," which is what is returned by .toString() you can say:

allAnswers = allAnswers.join(", ");

OR

data: {'answers': allAnswers.join(", ");

Important:

It is important to note that your .each() loop will break if you use .toString() in that way.

Broken

$('input[id="answer"]').each(function(){
    allAnswers.push($(this).val());
    allAnswers = allAnswers.toString(); 
});

The above code will not work because after the first iteration, allAnswers will be a string, therefore, calling .push() will throw an exception because .push() is not a function of string.

Fixed

$('input[id="answer"]').each(function(){
    allAnswers.push($(this).val());  
});
allAnswers = allAnswers.toString();

This code fixes the issue by converting the array to a string after you are done appending values to the array.

Community
  • 1
  • 1
mhodges
  • 10,938
  • 2
  • 28
  • 46
1

if you want all questions saved in string format, you can use json_encode

<?php

    $user_answer = $_POST['answers'];
    $date = date('d-m-Y h:i:s');

    $ques = json_encode($user_answer);

    $query = "INSERT INTO made_questions (lesson_id, user_answer, datum) VALUES ('1', '$ques', '$date')";
        mysqli_query($conn,$query) or die (mysqli_error($conn));

?>

warning : your code is not safe !

Think Big
  • 1,021
  • 14
  • 24
0

You should convert your array into a string before concatenating it in sql.

$arr = implode(",", $user_answer);
Ronald
  • 73
  • 7
  • This does not address the root of the issue, which is the OP thinking that .toString() modifies the original variable. OP clearly wants a string to be passed in the ajax call – mhodges Jun 16 '16 at 18:40
  • Passing an array in a sql will output a literal word Array. His problem is in the passed data in the database. And I see no problem with his javascript. – Ronald Jun 16 '16 at 18:43
  • 1
    You seeing no problem with his javascript was the reason for my comment. Yes, syntactically, his javascript is correct. Logically, it does not make sense. He is calling .toString() without assigning it to anything, and then passing the original (un-stringified) array into his AJAX call, which is what is causing issues. Also, if it was converting it to a string inside of the .each(), the 2nd iteration would cause an error because .push() is not a function of a string. – mhodges Jun 16 '16 at 18:47
  • Oh yes, I guess you're right, I had edited my answer. This function is a server side, it may have same results with the join function in javascript assuming an array is passed in the $_POST. – Ronald Jun 16 '16 at 18:59