Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 96
  • Last Modified:

PHP foreach DB query

Hi,

I have a long list of tick boxes where i select multipul items, i then have a foreach once the form is submited where i'm trying to do a datebase query, but it dopesnt work I can see the id'd being passed over but the query will only run once, what is the best practice to do this.

<input name='selectedchild[]' type='checkbox' value='{$row['id']}'>
           <input name='selectedchild[]' type='checkbox' value='{$row['id']}'>
           <input name='selectedchild[]' type='checkbox' value='{$row['id']}'>

Open in new window


foreach($_POST['selectedchild'] as $id)
{
		mysql_query("INSERT INTO outings (child_id) VALUES(".$id.")");
		  
		$query = "select email,email2 FROM child WHERE id = ".$id."";
		$result = mysql_query($query );

		$email=mysql_result($result ,$i,'email');
		$email2=mysql_result($result ,$i,'email2');

		$mail->Addbcc($email);
		if ($email2 != ""){
		$mail->Addbcc($email2);
		
		}
}

Open in new window


Thanks Simon
0
pc-buddy
Asked:
pc-buddy
  • 2
1 Solution
 
Ferruccio AccalaiSenior developer, analyst and customer assistance Commented:
FIrst of all I'd check for the result of the very first query.
Furthermore how do you check if there's any error?
Let's say that without assigning the first query to a result, in your loop the code could go to execute the second query while the first is already working.
So I'd do something like:
foreach($_POST['selectedchild'] as $id)
{
		$insert_result = mysql_query("INSERT INTO outings (child_id) VALUES(".$id.")") or die(mysql_error());;
		  
		$query = "select email,email2 FROM child WHERE id = ".$id."";
		$result = mysql_query($query ) or die(mysql_error());;

		$email=mysql_result($result ,$i,'email');
		$email2=mysql_result($result ,$i,'email2');

		$mail->Addbcc($email);
		if ($email2 != ""){
		$mail->Addbcc($email2);
		
		}
}

Open in new window

0
 
pc-buddyAuthor Commented:
Hi,

I still only get 1 result from the query ?

Thanks Simon
0
 
pc-buddyAuthor Commented:
I stand corrcted, its working

Thanks
0
 
Julian HansenCommented:
You might want to do some sanity checking on the $_POST before using it in a foreach. You have no guarantee that was is posted is what you expect.

Something like

$selected = isset($_POST['selectedchild']) ? $_POST['selectedchild'] : false;
if ($selected && is_array($selected)) {
   // selectedchild is set AND it is an array so proceed with foreach
   foreach($selected as $id) {
   ...
   }
}
else {
  // handle invalid input
}

Open in new window

2

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now