Forum Moderators: coopster

Message Too Old, No Replies

MySQL insert query and a foreach loop

         

scott182

4:12 pm on Nov 4, 2005 (gmt 0)

10+ Year Member



I am trying to insert the contents of an array into a database, with a separate row for each item of the array. However, no matter what the size of the array, the last element is never inserted into the database, but a print or echo inside the loop prints each element of the array correctly. Any ideas? This is getting very frustrating.

Thanks

<?php

require_once("mysql_connect.php");
$db = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_NAME,$db) or die(mysql_error() . "\n");

# get variables from form
while(list($key, $value) = each($_POST)){
$vars[$key] = $value;
}

$category_array = explode(' ', $vars[categories]);
$num_categories = count($category_array);
$item_id = time(); # set item id to current UNIX time
$todays_date = date("Y-m-d"); # date entered

$insert_item = "INSERT INTO todo (item_id, item, item_notes, date_enter, enter_by, event_date) VALUES ($item_id, '$
vars[description]', '$vars[item_notes]', $todays_date, '$vars[enter_by]', '$vars[event_date]')";

mysql_query($insert_item,$db);

foreach($category_array as $a_category){
print "$a_category<br />";
$insert_category = "INSERT INTO todo_categories (item_id, category) VALUES ($item_id, $a_category)";
mysql_query($insert_category,$db);
}

?>

jatar_k

4:29 pm on Nov 4, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld scott182,

maybe try a die on your queries to see if it is returning an error that you can't see

mysql_query($insert_category,$db) or die(mysql_error());

scott182

5:12 pm on Nov 4, 2005 (gmt 0)

10+ Year Member



Thanks. That helps. For example, if my array contains (cat1, cat2, cat3), I get the error 'Unknown column 'cat1' in 'field list'" For some reason it seems to be evaluating $a_category into the MySQL field 'category'. Interestingly, this does not occur if the category I'm trying to insert contains no letters.

jatar_k

5:26 pm on Nov 4, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



that's because you need single quotes around strings when inserting

$insert_category = "INSERT INTO todo_categories (item_id, category) VALUES ($item_id, '$a_category')";

scott182

5:34 pm on Nov 4, 2005 (gmt 0)

10+ Year Member



Perfect. Thanks so much for your help.