0

This is in reference to the post made here: insert multiple rows via a php array into mysql

My question is, can anyone explain this in more detail? I dont understand what $data and what $row is or does.

I'm pulling in many variables from a form like: $Customer = $_POST['Customer']; So if someone can show an example of how to use this code with multiple variables, it would be real nice.

$sql = array(); 
foreach( $data as $row ) 
{
    $sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));
Community
  • 1
  • 1
Mike
  • 13
  • 3

1 Answers1

1

from: PHP: foreach - manual

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

In this code, $data is an array. On each iteration, foreach will assign the value of the current row to $row. This is equivalent to:

for($i=0;$i<sizeof($data);$i++)
{
    $row = $data[$i];
    //use $row however u want
}

For example:

$data[0]['text'] = 'text for category1';
$data[0]['category_id'] = '1';

$data[1]['text'] = 'text for category2';
$data[1]['category_id'] = '2';

$data[2]['text'] = 'text for category3';
$data[2]['category_id'] = '3';

After running your foreach using this $data variable, if you use var_dump($row), you will get something like this:

array(3) {
  [0] =>
  string(25) "("text for category1", 1)"
  [1] =>
  string(25) "("text for category2", 2)"
  [2] =>
  string(25) "("text for category3", 3)"
}

The last line will implode this array to create a valid mysql query.

PS: By the way, mysql extension is deprecated. You should learn mysqli - mysql improved or mysql pdo - php data objects

Gabriel Moretti
  • 676
  • 8
  • 23