Member Avatar for dan_ord

Hi all,

I'm currently having an issue with an array, which when i loop through it, it returns random results, or only 1 result even though it should contain more.

What i doing atm is calling some information from a database and displaying it.

im outputting a hidden field with a value in it, an input box for a price to go in and also a check box so that i can check which options i want to include. Code example below:

<?php 
			 $qm = "SELECT * FROM models WHERE gen_id = '$gen_id'";
			  $rm = mysqli_query ($dbc, $qm) or trigger_error("Query: $qm\n<br />MySQL Error: " . mysqli_error($dbc));
			  
				  if (mysqli_affected_rows($dbc) == 0) { // No results.
					echo 'No models found';
				  } else {
			  
				  while ($rowm = mysqli_fetch_array($rm, MYSQLI_ASSOC)) {				  
					echo '<input name="model[]" type="hidden" value="'.$rowm['model'].'" /> '.$rowm['model'] . ' - Additional Price: <input name="model_price[]" type="text" id="model_price[]" size="4" /> <input name="checked[]" type="checkbox" id="checked[]" /><br>';
				}
			  }
		?>

Now when i submit my form, it should post the values and then insert data into my DB based on what i checked previously.

The problem i'm getting is the price is very random, depending on which boxes i tick, depends on what prices get stored in the array. Code Example Below:

$checked = $_POST['checked'];
					$model = $_POST['model'];
					$countm = count($checked);
					$model_price = $_POST['model_price'];
					
					for($i=0;$i<$countm;$i++){
						$model_name = $model[$i];
						$model_prices = $model_price[$i];

							$q3 = "INSERT INTO product_models (prod_id, model_name, added_price) VALUES ('$prod_id', '$model_name', '$model_prices')";
							$r3 = mysqli_query ($dbc, $q3) or trigger_error("Query: $q3\n<br />MySQL Error: " . mysqli_error($dbc));
						}

I've used very similar code before and it works fine, however if i tick 2 boxes it will only ever get the first price and not the second!

Am i missing something out from my code? Any help would be greatly appreciated!

I have made few change in your code. I hope it will work as expected.

page 1, line 8

$i=0; 
while.....

page 1, line 10
changed only portion of check box element, removed id=checked[] and added value attribute

<input name="checked[]" type="checkbox" value="'.$i++.'" />

page 2, line 7 and 8

$model_name = $model[$checked[$i]];
	$model_prices = $model_price[$checked[$i]];
Member Avatar for dan_ord

Hi urtrivedi,

Thanks, that worked perfectly!

Regards,

Dan

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.