Jump to content

[SOLVED] How to alter last iteration in a for() loop?


croakingtoad

Recommended Posts

Currently I have a for() loop building a query for me.  The code is as below-

for ($i = 0; $i < count($array); $i++) {

	//removes characters in $chars from $array items
	$chars = array(" ", "&", "(", ")", "/", "-");
	$trim = str_replace ($chars, "", $array[$i]);

	$query1 .= "$trim, ";
	$query2 .= "'$" . "_POST[$trim]', ";
}

$query1 = str_replace ("_1", "", $query1);

$query = "INSERT INTO 2007_results (name, email, ip, $query1) VALUES ('$name', '$email', '$ip'," .  $query2 . ")";
mysql_query($query);

 

This is producing a $query that looks like this--

$query = "INSERT INTO 2007_results (name, email, ip, query1.1, query1.2, ) VALUES ('foo', '[email protected]', '127.0.0.1', 'result1', 'result2', )";

 

Obviously that is producing a SQL error because of the extra comma and space inserted at the end of each iteration.  The question is, how to remove the inserted ", " on the last iteration?  There are many more inserted vars as part of $query1; I just shortened it for this example.

 

Thanks in advance!

If your table really is super dynamic and can somehow add fileds dynamically you could also use implode instead of loops and concatination. eg;

 

<?php

  $fields = array('foo','bar','bob');
  $values = array('this is foo','this is bar','this is bob');

  $sql = "INERT INTO tbl (" . implode(",",$fields) . ") VALUES ('" . implode("','",$values) . "')";

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.