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', 'foo@bar.com', '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!

Link to comment
Share on other sites

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) . "')";

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.