phil Posted October 7, 2003 Share Posted October 7, 2003 this works fine: <?php session_start(); $user = $_SESSION [\'user\' ] ; $user_id= $_SESSION [\'user_id\' ] ; $item1=$HTTP_POST_VARS[item1]; $item2=$HTTP_POST_VARS[item2]; $item3=$HTTP_POST_VARS[item3]; require_once(\'../Connections/camelgrooves.php\'); $sql= \"INSERT INTO test1 (id, user_id, item1, item2, item3) VALUES (\'\',\'$user_id\', \'$item1\', \'$item2\', \'$item3\')\" ; mysql_db_query ($database_camelgrooves,$sql,$camelgrooves); ?> now, the same function should be used with different tables (similar structure but different number of columns (id, user_id, item1, item2, ...itemx). i can\'t figure out how to get the variables and how to write the $sql string. i\'d lik to be able to do this test1 form => 8 form variables sent => INSERT INTO test1 (id, user, item1, ...item6) and this test2 form => 10 form variables sent => INSERT INTO test2 (id, user, item1,...item8) and ... can somebody help me? Link to comment https://forums.phpfreaks.com/topic/1130-insert-x-values-in-x-columns/ Share on other sites More sharing options...
Dissonance Posted October 8, 2003 Share Posted October 8, 2003 Here you go. A working example on the house. [php:1:791ebc7cf4]<?php error_reporting ( E_ALL ); # Just a dummy value. $user_id = 100; if ( isset ( $_POST[\'submit\'] ) ) { # Begin the first part of the query. We\'ll manually specify # the id and user fields. $sql = \"INSERT INTO test1 ( id, user\"; # Create the fields to work with. for ( $i = 1; $i < count ( $_POST ) - 2; $i++ ) { $sql .= \", item$i \"; } # Create the insertion values. $sql .= \") VALUES ( \'\', \'$user_id\'\"; for ( $i = 1; $i < count ( $_POST ) -2; $i++ ) { $sql .= \", \'$item$i\'\"; } $sql .= \" )\";\"; # Echo out the query to see if it meets your approval. echo $sql; } else { # Just a sample form for you to mess with. Alter the $fields # variable to change the number of form fields rendered. # The number rendered will be $fields minus 1, so \'11\' will # output 10 fields. This does NOT include the id and user_id # fields. $fields = 11; echo \"<form method=\"post\" action=\"\" . $_SERVER[\'PHP_SELF\'] . \"\">n\"; for ( $i = 1; $i < $fields; $i++ ) { echo \"<p>$i <input type=\"text\" name=\"item$i\" /></p>n\"; } echo \"<input type=\"submit\" name=\"submit\" value=\"Submit\">n\"; echo \"</form>n\"; } ?>[/php:1:791ebc7cf4] Link to comment https://forums.phpfreaks.com/topic/1130-insert-x-values-in-x-columns/#findComment-3836 Share on other sites More sharing options...
phil Posted October 8, 2003 Author Share Posted October 8, 2003 Fantastic answer; thanks very much. Ciao Phil Link to comment https://forums.phpfreaks.com/topic/1130-insert-x-values-in-x-columns/#findComment-3845 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.