0

Update

I have updated my code according to phant0m's suggestion. It still doesn't quite work yet, though: question_id is always 0 in the database, even though it's not in the array:

var_dump($_POST['question_id'])
array(2) { [0]=> string(2) "22" [1]=> string(2) "23" } 

The query:

string(122) "INSERT INTO student_score(course_uid, student_uid, question_uid, answer) VALUES
(1, 4, 0, 'answer1'), 
(1, 4, 0, 'answer4')

This is the new code:

$sql_data = array();
$sql_prefix = "INSERT INTO student_score(course_uid, student_uid, question_uid, answer) VALUES";
foreach($_POST['answer'] as $id => $answer){
    // don't use $_REQUEST!
    $course_id = (int) $_POST['course_id'][$i];
    $student_id  = (int) $_POST['student_id'][$i];
    $question_id   = (int) $_POST['question_id'][$i];
    $answer      = mysql_real_escape_string($answer);
    $sql_data[] = "($course_id, $student_id, $question_id, '$answer')";
}
$sql = $sql_prefix.implode(", \n", $sql_data);
var_dump($sql);
if(!mysql_db_query($dbName, $sql, $connect)){
    $_SESSION['msg'] = "Could not save information, Please try again";
    header("Location:student_assignment.php");
    //replaced die with else clause
}
else{
    $_SESSION['msg'] = "Question successfully created";
    header("Location:student_assignment.php");
}

Initial question:

I have a problem adding the values of an array into a mysql database. The thing is I have two loops and if I add the INSERT in one of the then the other one gives the wrong value. But if I echo inside each loop it gives the right values.

At the moment it adds two double rows of each value where I only want one row of each value.

Here is my code:

<?php
  require_once("settings.inc.php");

  // require_once("student_session.inc.php");
  session_start();

  for ($d = 0; $d <= count($_POST[answer]); $d++) {
      $answer = $_POST[answer][$d];//I want to insert this value          
      //echo $answer;
      $ids = $_REQUEST['question_id'];

      foreach ($ids as $value) {
          //echo $value; //and this value into the INSERT              
          $sql = "INSERT INTO student_score(answer) VALUES ('$answer')";
          $results = mysql_db_query($dbName, $sql, $connect);
      }
  }

  if (!$results) {
      $_SESSION['msg'] = "Could not save information, Please try again";          
      header("Location:student_assignment.php");          
      die;
  }    

  $_SESSION['msg'] = "Question successfully created";      
  header("Location:student_assignment.php");

  die;
?>
Community
  • 1
  • 1
Annuscha
  • 3
  • 4
  • 7
    Can you reduce the code so only the relevant part remains? Please try to explain your problem better. Also: Nobody wants to read unindented code! – phant0m Jul 11 '11 at 12:34
  • Sorry this is my first post, on the submit page there is a for loop that gets the array of the answers selected. Then there is a foreach that get the question id's. My question is how will I get the values of the loops into a INSERT query multiple times? – Annuscha Jul 11 '11 at 12:42
  • You can loop through the array multiple times. Anyway, I suggest you take a look at multi-insert statements. What you are doing is highly inefficient. – phant0m Jul 11 '11 at 12:44
  • What do you mean inefficient?What am I doing wrong? – Annuscha Jul 11 '11 at 12:47
  • The only thing I want to do is add the values in the loop into a database. – Annuscha Jul 11 '11 at 12:50
  • You send a query for every INSERT, you could to a batch-insert for example. – Jacob Jul 11 '11 at 12:53
  • How would I do that sorry to bother, I have been busy with this since yesterday.not even google is helping. – Annuscha Jul 11 '11 at 13:04
  • My code shows you how to insert multiple entries at once. – phant0m Jul 11 '11 at 13:13
  • Can you please put all debugging code in at once? Also: Add `echo "\nvariable: ".$question_id."\nPOST: ".$_POST['question_id'][$i]."\n";` below `$sql_data[]` and then copy the results from *source view* – phant0m Jul 11 '11 at 18:40
  • variable: 0 POST: variable: 0 POST: – Annuscha Jul 12 '11 at 05:59
  • that's what I got adding that line of code – Annuscha Jul 12 '11 at 06:00
  • Can someone please help me I have tried everything :'( – Annuscha Jul 12 '11 at 08:57

3 Answers3

0

You're using the wrong variable:

"INSERT INTO student_score(answer) VALUES ('$answer')";

You comment that the variable you'd like inserted is called $value, so you meant to write:

"INSERT INTO student_score(answer) VALUES ".
       "('".mysql_real_escape_string($value)."')";

(mysql_real_escape_string is to prevent SQL injection attacks)

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
0

Your code does not make much sense.

This might more closely resemble what you want it to do:

// you will not want <=, that will create an index error upon the last 
// iteration, also, you need to quote the key!
// This is fixed:
//for ($d = 0; $d < count($_POST['answer']); $d++) {
// this is a better way
// this assumes, that the indices of the POST array nicely correspond with each 
// other.
$sql_data = array();
$sql_prefix = "INSERT INTO student_score(question_id, student_id, course_id, answer) VALUES";
foreach($_POST['answer'] as $id => $anwer){
    // don't use $_REQUEST!
    $question_id = (int) $_POST['question_id'][$i];
    $student_id  = (int) $_POST['student_id'][$i];
    $course_id   = (int) $_POST['course_id'][$i];
    $answer      = your_escape_function($answer)
    $sql_data[] = "($question_id, $student_id, $course_id, '$answer')";
}
$sql = $sql_prefix.implode(", \n", $sql_data);
if(!mysql_db_query($dbName, $sql, $connect)){
    $_SESSION['msg'] = "Could not save information, Please try again";
    header("Location:student_assignment.php");
    //replaced die with else clause
}
else{
    $_SESSION['msg'] = "Question successfully created";
    header("Location:student_assignment.php");
}

Attention

This code is mostly based on guesswork and assumptions what you want it to do. You need to have a function that properly escapes your code based on whether magic_quotes are enabled. Simply calling mysql_real_escape_string()as suggested in the other answer is incorrect.

Please note that mysql_* functions are outdated. Consider using parameterized queries using PDOs or myqsli.

PS: do not use $_REQUEST.

phant0m
  • 16,595
  • 5
  • 50
  • 82
  • Thank you very much for your help, everything works fine except the question id is 0 in the database. Would you maybe know why? – Annuscha Jul 11 '11 at 14:05
  • I suggest you add `var_dump($_POST['question_id']);` above the `foreach`-line. Post back the output. – phant0m Jul 11 '11 at 14:07
  • array(2) { [0]=> string(2) "22" [1]=> string(2) "23" } array(2) { [0]=> string(2) "22" [1]=> string(2) "23" } array(2) { [0]=> string(2) "22" [1]=> string(2) "23" } array(2) { [0]=> string(2) "22" [1]=> string(2) "23" } – Annuscha Jul 11 '11 at 14:14
  • Hmm... this is certainly interesting. It should be converted to an integer without problems with (int). Could you post back the output of `var_dump($sql);` by inserting it above `if(!mysql_db_query()` ? – phant0m Jul 11 '11 at 14:18
  • string(122) "INSERT INTO student_score(course_uid, student_uid, question_uid, answer) VALUES(1, 4, 0, 'answer1'), (1, 4, 0, 'answer4')" – Annuscha Jul 11 '11 at 14:20
  • Ah, you have adjusted my code. Can you update your initial question and *add* the modified code at the bottom please, so I can see the modifications. – phant0m Jul 11 '11 at 14:26
  • I added the code to my original code, Sorry for the layout I don't know how to add it in code view. The only things I changed was the column names and the order. – Annuscha Jul 11 '11 at 14:39
  • @Annuscha: Oh sorry, that drowned in my inbox... Yes, let me think a little ;) – phant0m Jul 11 '11 at 16:18
0

make use of MySQL transactions: PHP + MySQL transactions examples

Also can you post the output of the following?: print_r($_POST); and print_r($_POST[answer]);

Using $_REQUEST is bad Idea. either use POST or GET explicitly!

Community
  • 1
  • 1
Stefano Mtangoo
  • 6,017
  • 6
  • 47
  • 93
  • why is using $_REQUEST is bad Idea? – Lawrence Cherone Jul 11 '11 at 13:21
  • Because you don't know whether it is post or Get. Suppose the same file receives form but one via Get and another POST using same index, how do you differentiate? It is bad practice--->be explicit! – Stefano Mtangoo Jul 11 '11 at 14:17
  • @Lawrence, but `$_REQUEST` also includes stuff from `$_SESSION`. Also, `$_POST` is shorter to type. – TRiG Jul 11 '11 at 14:42
  • @Lawrence: Your argumentation is invalid. By default, the order is "gpc", i.e. `GET` has the highest priority. A user could be sent a link to a form, and depending what the `action` is set to, the `GET` parameters may be preserved and thereby overriding a value by the user. $_REQUEST also makes debugging harder, because you never really know which value you were originally refering to. There is **no** benefit in using it. As already mentioned, it's also longer... so be pragmatic at least ;) @TRiG: No it doesn't. It may also contain content from `$_COOKIE` – phant0m Jul 11 '11 at 18:29