Sean Stapleton Sean Stapleton - 5 months ago 8
SQL Question

For loop only firing once, inputting incorrect values into mysql database

First off, I know that there is deprecated code in my example, I'm working with a platform I designed a while ago and have not yet finished updating it all to use mysqli instead, so I'm making some minor edits to the existing platform.

So I have a form that creates inputs based on categories inputted in a different table, the form outputs correctly but repeats the same name (points and cat) for each category that exists.

According to another post (How to insert the dynamic table row data into database at once) inserting this data into my table can be accomplished with a for loop as shown in my example.

The issue I'm having is that it's only firing once, despite the fact that the array it creates should have 4 inputs. Also, the data that is being sent to the table column "cat_id" is "3" which could either be the first digit of the cat_id it's using, or the last array iteration [0], [1], [2], [3].

This is my first question, so I apologize if all the details needed are not provided, I will gladly update if anything else is needed.

$cat_id = $_POST['cat'];
$points = $_POST['points'];

$count = count($cat_id);

for ($i = 0; $i < $count; $i++) {

$sql = "INSERT INTO scoring (cat_id, points) VALUES ('$cat_id[$i]','$points[$i]')";
$query = mysql_query($sql);

}


EDIT: Updated code based on suggestions.

Answer

The question/answer you linked are incorrect. Arrays are not built dynamically by default in HTML:

To get your <form> result sent as an array to your PHP script you name the <input>, <select> or <textarea> elements like this:

 <input name="MyArray[]" />
 <input name="MyArray[]" />
 <input name="MyArray[]" />
 <input name="MyArray[]" />

http://php.net/manual/en/faq.html.php#faq.html.arrays

So I presume you currently have

<input name="cat">
<input name="cat">

which will only process as one cat element. This causes your 1 iteration.

Try:

<input name="cat[]">

for each field. To debug this in the future use print_r or var_dump to output what you think a variable contains.

Also use mysql_real_escape at a minimum while you update your driver to something that can handle parameterized queries.