0

I have a page that contains the allows a user to enter up to 10 records in a database. The problem I'm having is that in many (most) cases, the user will only enter one or two records in, but the database insert is processing all of the blank records and inserting them as well. I've configured the DB to not accept NULL values, but I suspect the blank values are not quite equivalent to NULL and that's why the records are still being inserted. How can I code this so that blank records are not inserted into the database.

Current Insert Code:

    <?php
if (isset($_POST['submit'])) {  

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

$indtypeid = $_POST['indtype'][$i];
$indicator = $_POST['indicator'][$i];
$actorid = $_POST['actor'][$i];
$reportid = $_POST['report'][$i];

print 'Row ' . $i . ': '  . $indtypeid . '-' . $indicator . '-' . $actorid . '<br/>';

$qry_digestreport = "INSERT INTO indicator (indtypeid,indicator,actorid,reportid) VALUES ('$indtypeid', '$indicator', '$actorid', '$reportid')";


if (!mysql_query($qry_digestreport,$connection))
  {
  die('Error: ' . mysql_error());
  }
echo "<br/>Records added!<br/>";

1 Answer 1

2

A simple if() check would do:

if (empty($indtypeid) || empty($indicator) || ....) {
   continue; // jump to next loop iteration
}

right after your $_POST assignments.

Note that your code is utterly vulnerable to SQL injection attacks, so you might want to read a bit about that on http://bobby-tables.com

Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm. Many thanks. A bit of a novice at this, so planning to get input validation sorted out after I get the core functionality working. The link you provided should be of some good help as well. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.