0

This is my current output from a preg_match_all

Array
(
[0] => Array
    (
        [0] => 2 Sentence text here
    )

)

Array
(
[0] => Array
    (
        [0] => 3 Sentence text here.
        [1] => 4 Sentence text here.
        [2] => 5 Sentence text here.
    )

)

I'm trying to insert each output as a new row in a table but it's thinking that each [0] [1] [2] is a new column. How do I insert the array into mysql?

$query = "INSERT INTO table (col1) VALUES ";
foreach ($matches as $item) {
$query .= "('".$item[0]."'),";
}
$query = rtrim($query,",");
$result = mysql_query($query);

The above obviously only inserts the first row in of the array

1 Answers1

1

Well, you have an array in other array, so...

$query = "INSERT INTO table (col1) VALUES ";

if(!empty($matches))
{
    foreach ($matches as $item) {
        foreach ($item[0] as $items) {
            $query .= "('".$items."'),";
        }
    }
}

if(!empty($matches))
{
    foreach ($matches[0] as $item) {
        $query .= "('".$item."'),";
    }
}

Depends on how you are getting your array matches.


$query = rtrim($query,",");
$result = mysql_query($query);

That way you'll get this query:

INSERT INTO table (col1) VALUES ('2 Sentence text here'), ('3 Sentence text here'), ('4 Sentence text here'), ('5 Sentence text here')

Which is a valid way to insert several values in one column with a single INSERT statement.

Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Luigi Siri
  • 2,068
  • 2
  • 19
  • 27