0

I have an array called "questions" that I am trying to INSERT into mysql with foreach. Array looks like this:

    Array
    (
    [0] => Array
        (
        [booking_id] => 936
        [question_id] => a
        [value] => 4
        )

    [1] => Array
        (
        [booking_id] => 936
        [question_id] => b
        [value] => 3
        )

    [2] => Array
        (
        [booking_id] => 936
        [question_id] => c
        [value] => 2
        )

    [3] => Array
        (
        [booking_id] => 936
        [question_id] => d
        [value] => 1
        )
     )

FOREACH looks like this:

$sql = array(); 
foreach( $_POST['questions'] as $row ) {

    $sql[] = '("'.$row['booking_id'].'", "'.$row['question_id'].'", '.$row['value'].')';
}

mysql_query('INSERT INTO table (booking_id, question_id, value) VALUES '.implode(',', $sql));

The foreach simply inserts the first item in the array into the table and doesn't loop through the entire array.

Any ideas where I am going wrong?

5
  • Are you sure that $_POST contains what you think it does? Commented Jan 14, 2014 at 3:46
  • print_r($_POST['questions']); gives the above array Commented Jan 14, 2014 at 3:48
  • all booking_id is 936 ..? Commented Jan 14, 2014 at 3:50
  • If booking_id is your primary key and cannot have duplicates and every record has id=936 then that's your problem. Try adding ` or die(mysql_error())` to the end of your mysql_query() statement. Commented Jan 14, 2014 at 3:52
  • spotted the problem - it's the primary key. obviously not meant to be. thanks. Commented Jan 14, 2014 at 4:00

3 Answers 3

2

It's already time to use PDO or MySQLi with PHP. This is a working example. You could replace $arr with $_POST and refactor a bit to suit your needs.

$mysqli = new mysqli('localhost', 'root', '', 'dachi');

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$arr = array(
  array(
    'booking_id' => 936,
    'question_id' => 15,
    'value' => 4,
  ),
  array(
    'booking_id' => 936,
    'question_id' => 15,
    'value' => 3,
  ),
);

foreach ($arr as $rec) {
  $stmt = $mysqli->prepare("INSERT INTO `test` (`booking_id`,`question_id`,`value`) VALUES (?,?,?)");
  // You will probably need to change 'iii'
  // i = integer
  // s = string
  // So you might have something like isi if you need like that or sss
  $stmt->bind_param('iii', $rec['booking_id'], $rec['question_id'], $rec['value']);
  $d = $stmt->execute();
  $stmt->close();
}
Sign up to request clarification or add additional context in comments.

5 Comments

does mysqli/PDO require an install on the server? just got back into all this for a new project and it seems like a bit has changed!
You have to install PDO php.net/manual/en/pdo.setup.php but the mysqli extension was introduced with PHP version 5.0.0.
Btw, your code is not secure. rumor that is "truish": Nowadays 'everyone' is using prepared statements for security
I know. I was going to run mysql_real_escape_string on the variables. Looks like this method is a bit outdated though.
mysql is deprecated as stated on php website. php.net/manual/en/function.mysql-real-escape-string.php You can see it in red.
2

I've actually duplicated the code and got it run on an actual MySQL server perfectly, no mistakes in the code as far as I can see.

The only problem I can guess is a unique index that prevents from adding multiple records under the same booking_id.

Is there a primary / unique index on the booking_id field that prevents from adding multiple records?

5 Comments

Why the downvotes? This seems like something worth looking into.
@maackle If someone has something to ask about the question, it should be a comment. If they are trying to answer the question, it should be worded as an answer.
@msg7086 - thanks. that is indeed the problem. many thanks. silly thing to miss.
@winterblood Thanks for the tip. I'm new to the community and not that good in constructing my words. It's really hard for me to ask for a clarification in the comment without answering the question itself.
@msg7086 Don't worry, we were all new once, and the StackOverflow way of doing things can be very particular sometimes.
-2
// $sql query value to get data in DB
$branches= array();
$sql = array();
while ($row = mysql_fetch_array($sql))
{
  array_push($question, $row);

}
 // this part to loop data fetch in sql
   $branch_type = '';
   foreach ($question as $NBU) {

    $sql[] = '("'.$row['booking_id'].'", "'.$row['question_id'].'", '.$row['value'].')';

    }

   mysql_query('INSERT INTO table (booking_id, question_id, value) VALUES '.implode(',', $sql));

dont use $_POST['questions'] because foreach only read array data.

1 Comment

try to see if the variable is in array. the one you loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.