I am getting an error from a foreach statement, not sure why, here is the code:
PHP Code:
$new_prod_id = $count + 100;
function arrayQuery($f_prod_id,$table) { $sql=mysql_query("SELECT * FROM $table WHERE prod_id='$f_prod_id'"); if(mysql_num_rows($sql)) { return(mysql_fetch_assoc($sql)); // use fetch_assoc } return false; }
function createSpec($f_desc,$f_step_num,$f_prod_id) { $sql=mysql_query("INSERT INTO specs (descriptor,num,prod_id) VALUES ('$f_desc','$f_step_num','$f_prod_id')") or die (mysql_error()); }
$spec=arrayQuery($type,"specs");
$i=0
foreach($spec['descriptor'] as $descriptor) { createSpec($spec['descriptor'],[$i],$new_prod_id); $i++; }
"descriptor" is a column in the specs DB.
I am trying to write 27 rows in the specs database from a template created. I get the values using "$spec=arrayQuery($type,"specs");" and then I want to loop for each array value and create a new row in the specs DB.
This is the error I am getting:"Parse error: syntax error, unexpected T_FOREACH in"
Any help would be greatly appreciated.
02-11-2010, 01:11 AM
drumhrd
you need to put a semi colon after your $i variable is setup
$i=0(semicolon)
$i=0;
02-11-2010, 01:18 AM
Hampster
A couple things. $spec could be false. You can't run foreach on a boolean, so you may want to check that.
Secondly, $spec is a 1-dimensional array (assoc). $spec['descriptor'] is just a single element of the array. I may be missing something, but running foreach over one element is a bit wordy.
Oh, and the semicolon is missing in the previous line.
--Dave
02-11-2010, 10:51 AM
themonkey40
Hampster, do you have a better piece of code I can use. Basically I can't get the loop to run. I fixed the semicolon (late night mistake).
When I run the script now, I get an error that there is an unexpected [.
PHP Code:
$i=0;
foreach($spec['descriptor'] as $descriptor) { createSpec($spec['descriptor'],[$i],$new_prod_id); $i++; }
What I want to do here is run the loop every time there is a $spec['descriptor'] and write a new line in the database.
02-11-2010, 11:19 AM
criterion9
You are probably looking for:
while($row = mysql_fetch_assoc($mysql_resource)){
This would change your function a bit as well...
PHP Code:
function arrayQuery($f_prod_id,$table)
{
$sql=mysql_query("SELECT * FROM $table WHERE prod_id='$f_prod_id'");
if(!$sql){
//query failed;
return false;
}
if(mysql_num_rows($sql) != 0)
{
return($sql); // use fetch_assoc
}
return false;
}
...
PHP Code:
$spec=arrayQuery($type,"specs");
$i=0
while($row = mysql_fetch_assoc($spec)) {
//not sure how this will affect your other code as I didn't look
//this should give you a starting point for what you need
//createSpec($row['descriptor'],[$i],$new_prod_id);
echo "Row: ".$i."; "$row['descriptor']."<br />";
$i++;
}
02-11-2010, 06:14 PM
themonkey40
Thanks again criterion9. I used the while statement and it worked.