croakingtoad Posted July 15, 2007 Share Posted July 15, 2007 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! Quote Link to comment Share on other sites More sharing options...
trq Posted July 15, 2007 Share Posted July 15, 2007 You could try using rtrim, but Im failing to understand the logic here. You can't just keep adding fileds and values to your query, they need to match up with the fields that actualy exist in your table. Quote Link to comment Share on other sites More sharing options...
AndyB Posted July 15, 2007 Share Posted July 15, 2007 $one_character_less = substr($your_string, 0, -1); Quote Link to comment Share on other sites More sharing options...
trq Posted July 15, 2007 Share Posted July 15, 2007 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) . "')"; ?> Quote Link to comment Share on other sites More sharing options...
croakingtoad Posted July 16, 2007 Author Share Posted July 16, 2007 Great answers, thanks! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.