PHP loop

Hey guys,

I am trying to input data into a mysql database from data thats been added by a jquery form with cloned fields. It is working however it adds the first row correctly then a blank row and then the rest of the rows correctly

The code is this

$x=0;

do {
	$fga=$_POST['ID'.$x.'fga'];
	$fgm=$_POST['ID'.$x.'fgm'];
	$fta=$_POST['ID'.$x.'fta'];
	$ftm=$_POST['ID'.$x.'ftm'];
	$tpa=$_POST['ID'.$x.'tpa'];
	$tpm=$_POST['ID'.$x.'tpm'];
	$fta=$_POST['ID'.$x.'fta'];
	$ftm=$_POST['ID'.$x.'ftm'];
	$stl=$_POST['ID'.$x.'stl'];
	$trb=$_POST['ID'.$x.'trb'];
	$ast=$_POST['ID'.$x.'ast'];
	$blka=$_POST['ID'.$x.'blka'];
	$blkf=$_POST['ID'.$x.'blkf'];
	$tovr=$_POST['ID'.$x.'tovr'];
		
	 mysql_query("INSERT INTO stats (gameId, fga, fgm, tpa, tpm, fta, ftm, ast, stl, trb, blka, blkf, tovr) VALUES ('$gameId', '$fga', '$fgm', '$tpa', '$tpm', '$fta', '$ftm', '$ast', '$stl', '$trb', '$blka', '$blkf', '$tovr')")or die("<div class='errmsg'>Insert Error: ".mysql_error()."</div><br /> \n");
	
	$x++;

Can anyone see what ive done wrong?

Thanks

It’s pretty hard to say with the code you provided. I suspect that an iteration of $_POST doesn’t contain any info and that’s where your blank row is coming from. Do a print_r() on $_POST and make sure there are no skipping of $x in the array. Since you are blindly assuming that $_POST['ID.$x isset, it probably isn’t for one of the values of $x.

You could incorporate a isset() check on the $_POST to make sure the iteration of $x is valid for that loop. You can post the print_r results here for us to verify if needed. May also want to post some code of the form so we can see how that is being produced.

Lastly, PLEASE USE THE CODE TAGS TO POST CODE! It’s the php and # buttons above the smileys. Use the according button based on the kind of code being posted.

If you stopped using the deprecated mysql_query which will be completely removed from future PHP versions meaning your websites will one day cease to work [Source: http://php.net/manual/en/function.mysql-query.php] and started using something like PDO, you could simply use something like:

[PHP]
print_r($statement->errorInfo());
[/PHP]

Which would tell you what the error is…

Using PDO or MySQLi is so much more secure, here’s an example of PDO:

[PHP]

<?php $statement = $dbconn->prepare(" INSERT INTO yourtable (val1,val2,val3) VALUES (:val1,:val2,:val3) "); $result = $statement->execute([ ":val1" => $_POST['val1'], ":val2" => $_POST['val2'], ":val3" => $_POST['val3'] ]); if (!$result){ //There was an error, debug echo "
";
	print_r($sth->errorInfo());
	echo "
"; }else { //The insert was a success } ?>

[/PHP]

Sponsor our Newsletter | Privacy Policy | Terms of Service