Chris
Chris

Reputation: 545

MSSQL: multiple INSERTs with PHP arrays and echoing back the data

I have a form with the following structure:

<input type="text" name="projNo[1]" id="projNo[1]" value="<?php echo $row['ProjNo'
[1];>"
/>
<input type="text" name="projBudget[1]" id="projBudget[1]" value="<?php echo
$row['ProjBudget'][1]; ?>" />
<input type="text" name="projDateFrom[1]" id="projDateFrom[1]" value="<?php echo
$row['ProjDateFrom'][1]; ?>" />
<input type="text" name="projDateTo[1]" id="projDateTo[1]" value="<?php echo 
$row['ProjDateTo'][1]; ?>" />

<input type="text" name="projNo[2]" id="projNo[2]" value="<?php echo $row['ProjNo'
[2];>"
/>
<input type="text" name="projBudget[2]" id="projBudget[2]" value="<?php echo
$row['ProjBudget'][2]; ?>" />
<input type="text" name="projDateFrom[2]" id="projDateFrom[2]" value="<?php echo
$row['ProjDateFrom'][2]; ?>" />
<input type="text" name="projDateTo[2]" id="projDateTo[2]" value="<?php echo 
$row['ProjDateTo'][2]; ?>" />

There are two more groups like this with indexes 3 and 4. Upon submit, four separate records must be created in the DB if the user has filled in all four lines. My question is twofold: How would I structure my query to accomplish this? And: Have I set up my code correctly? When the form is loaded, I would like the correct output to be displayed. I've never been confronted with a request like this before, so I'm flying a bit blind.

Upvotes: 0

Views: 117

Answers (1)

Jan Schejbal
Jan Schejbal

Reputation: 4033

Use PDO and prepared statements. Prepare a statement like this:

$s = $db->prepare('INSERT INTO PROJECT (no, budget, from, to) VALUES (?,?,?,?)')

Execute the statement for each set like this:

for ($i = 1; $i<=4; $i++) {
    $s->execute(array($projNo[$i], $projBudget[$i], $projDateFrom[$i], $projDateTo[$i]));
}

(You need to add error checking and validation. This includes something that loads the stuff from $_POST to the arrays I used in the above example.)

Currently, you have a XSS security issue in your code. You cannot just echo stuff that comes from the user - you need to escape it. If you are putting it inside HTML, including double-quoted attribute values like in your case, use echo htmlspecialchars($_GET[...]);.

You may want to create a "htmlout" function that does nothing else than echo htmlspecialchars, just to have a nicer, easier-to-write name for it, and use it everywhere. That way, you can search your code for instances of "echo", and unless you have protected them otherwise, this indicates you probably need to add some escaping.

Upvotes: 1

Related Questions