Forum Moderators: coopster

Message Too Old, No Replies

Need help with php foreach loop

         

Shannonlp

12:18 am on Mar 6, 2009 (gmt 0)

10+ Year Member



I am trying to dynamically create a a mysql multiple insert statement. The code below only provides the last entry. i.e.


INSERT INTO customers(cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country)
VALUES('Pep E. LaPew',
'100 Main Street',
'Los Angeles',
'CA',
'90046',
'USA');

I want the result to be this.

INSERT INTO customers(cust_name,
cust_address,
cust_city,
cust_state,
cust_zip,
cust_country)
VALUES(
'Pep E. LaPew',
'100 Main Street',
'Los Angeles',
'CA',
'90046',
'USA'
),
(
'M. Martian',
'42 Galaxy Way',
'New York',
'NY',
'11213',
'USA'
);

If I just print within the foreach loop for $t2 it will print the results I am looking to achieve. The problem seems to be that I am only receiving the last output result not the entire loop.

$q = "INSERT INTO ".$table." (";

$query = 'DESCRIBE `' . $table . '`';
$result = mysql_query($query);
while($i = mysql_fetch_assoc($result)) {
$q .= $i['Field'].","."\n";
}

$q = substr($q, 0, -2);
$q .= ")";
$q .= " VALUES ";

$result = mysql_query("DESCRIBE $table");

$numfields = mysql_num_rows($result);

$post_var_chunks = array_chunk($post_var,$numfields);

foreach($post_var_chunks as $arry_input){

$t2 = "(";

for ($r = 0; $r <= $numfields-1; $r++) {

$t2 .= "' ".${$arry_input[$r]}. "'" . ",";

}
$t2 = substr($t2, 0, -1);

$t2 .= ')';
$t2 .= ',';

echo $t2;

}

$t2 = substr($t2, 0, -1);

$combined_sql = $q .= $t2;

$dynamic_sql = $combined_sql;

echo $dynamic_sql;

//$add_query = mysql_query($dynamic_sql) or die("BAD QUERY: $dynamic_sql<br><br>" . mysql_error());

wheelie34

10:45 am on Mar 6, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Looks like you closed the loop before it prints each one this means it will run through them all but only print AFTER looping thus only having one

while($i = mysql_fetch_assoc($result)) {
$q .= $i['Field'].","."\n";
} <---

Try moving the closing curly bracket to AFTER you echo statement.

HTH

Shannonlp

4:36 pm on Mar 6, 2009 (gmt 0)

10+ Year Member



I actually have resolved the problem. I forgot to declare $t2 = ''; &
$t2 .= substr($t2, 0, -1); forgot the "." This resolved the problem.