Jump to content


Photo

insert x values in x columns ?


  • Please log in to reply
2 replies to this topic

#1 phil

phil
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 07 October 2003 - 11:25 PM

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?

#2 Dissonance

Dissonance
  • Members
  • PipPip
  • Member
  • 12 posts
  • LocationChicago, IL

Posted 08 October 2003 - 01:52 AM

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]
Friends don't let friends vote Republican.

#3 phil

phil
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 08 October 2003 - 11:46 AM

Fantastic answer;
thanks very much.
Ciao
Phil




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users