-3

my array looks like:

Array
(
    [name] => Array
        (
            [0] => Matrix
            [1] => Ryan 
        )

    [surname] => Array
        (
            [0] => Relaoded
            [1] => Lose
        )

)

my problem is that, the key and value doesn't match the count.

How to insert this array like exact structure to mysql with PDO?

In mysql table

    ----------------------------------
   |    id      name      surname    |
   |    1       Matrix    Relaoded   |
   |    2       Ryan      Lose       | 
    ----------------------------------

of course i need solution programmatically.

I spent hours, to go trought this awesome forum, but i can't find solution :(

Thanks ;)

beater
  • 15
  • 2
  • 7

2 Answers2

2

@Zerkms was right, you need just to learn how to handle this array.
Easiest way would be

foreach($array['name'] as $key => $name) {
    $surname = $array['surname'][$key];
    // now you can use the pair
    var_dump($name,$surname);
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • thx, i have another question, how to insert this solution in mysql with PDO usin only one query – beater Feb 21 '13 at 21:17
  • Now my code looks like this: http://codepad.org/E5fnuSCq it's only insert last foreach values in 2 equialent rows – beater Feb 21 '13 at 21:43
0

Here's the SQL statement

INSERT INTO mytable (`id`,`name`,`surname`) VALUES(?,?,?);

then the following pseudocode:

for ($i = 0; $i < count($['name']); $i++) {
    $db->execute($i+1, $a['name'][$i], $a['surname'][$i]);
}
Philip Whitehouse
  • 4,293
  • 3
  • 23
  • 36
  • I would have had to to use `$key=>$value` and use the `$key` to get the surname. It seemed less logical given you were looping round two arrays. If surnames was longer it's easier to write `$i < count($['name']) || $ i < count($a['surname'])`. If it was the reverse (rows then columns) I would have used `foreach` because it's much neater. – Philip Whitehouse Feb 21 '13 at 20:41