If statement and empty string to DB

Hi,
Is there anything wrong with the if statement is this code?
Can an empty string by submitted to a database?

   if (isset($_POST['action']) and $_POST['action'] == 'hauptFormular')
{
  include $_SERVER['DOCUMENT_ROOT'] . '/cuislegibney/includes/db.inc.php';
 try
  {
      /*echo "<pre>";
    print_r($_POST);
    echo "</pre>";*/

    $j = ((count($_POST)-5)/3)-1;//counts number of forms. 
    //The five is the number of elements in $_POST not repeated: action, exam, year, subject and session. 
    //Then dividing this by 3 gives the number of rows and -1 because we want to start at 0 not 1.

    for ($i = 0; $i <= $j; $i++) {
    $exam = $_POST['exam'];
    $year = $_POST['annual'];
    $subject = $_POST['subject'];
    //$session = isset($_POST['session']) ? $_POST['session'] : "";//ternary operator
    if(isset($_POST['session'])){
      $session = $_POST['session'];
    } else {
      $session = "";
    }
    $result = $_POST['result' . $i];
    $first = $_POST['first' . $i];
    $last = $_POST['last' . $i];

    $sql = 'INSERT INTO halbForm SET 
        exam = :exam,
        year = :year,
      subject = :subject,
      session = :session,
      result = :result,
        first = :first,
        last = :last';
                $s = $pdo->prepare($sql);
                $s->bindParam(':exam', $exam);
                $s->bindParam(':year', $year);
                $s->bindParam(':subject', $subject);
                $s->bindParam(':session', $session);
                $s->bindParam(':result', $result);
                $s->bindParam(':first', $first);
                $s->bindParam(':last', $last);
                $s->execute();
              }
  }
  catch (PDOException $e)
  {
    $error = 'Error inserting into halbForm.';
    include 'error.html.php';
    exit();
  }
  //include 'input.html.php';
  header('Location: .?input');
  exit();
}

The above is sending nothing to the DB if there is no value for $_POST[‘session’].
Thanks,
Shane

Do you get any error messages?

Your code doesn’t seem to be malformed, so I imagine the if statement is being evaluated correctly.

It’s possible to place restrictions on DB column types, along with default values and whether that field is allowed to be null. I’ll assume you’re using a MySQL database here, in which case you can run the following query to get some information about your table schema:

DESCRIBE halbForm;

The resulting output will give you information regarding the column types and rules regarding records in that table. That might lead you to the answer to your question about empty strings. FWIW, it is perfectly acceptable to store an empty string a database field.

Looking at the code though, I wonder which path is being executed. When you are having the issue with the record not being saved to the database, are you catching your PDOException and echoing out your error message on your error.html.php page? If this is the case, you could get some more helpful information from the PDOException:

catch (PDOException $e)
{
    print_r($e); // Add this line
    $error = 'Error inserting into halbForm';
    include 'error.html.php';
    exit();
}

Warning - Shameless plug for my github project following:

You may also want to perform some more analysis on your query, which can be troublesome using PDO’s prepared statements. If you’ve exhausted your other troubleshooting steps and would like to see an example of what the query being executed actually looks like, you can try using this project to simulate that query:

I think that is exactly what it is. Here is a screen shot of the table structure.

I just changed that column to allow it to be NULL and I am sure that that is it. But I have been trying to get the form to do other things and at the moment it isn’t working and won’t be until I fix that and so i can’t actually see just now if it is working or not. But I am sure that that was the problem and will post again as soon as i know.
Thanks for you help.
Shane

1: Advise against using “and” as opposed to &&. [Reference][1]. While it doesnt interfere with you here, I could in the future.
2: Dont give your form items different names in this way. Instead label them as name=“result” and then handle them on a per-row basis.
3: Is ‘session’ a checkbox? If it’s a text box, it will always be ‘set’ even if empty.
4. Do all of this:

$exam = $_POST['exam'];
$year = $_POST['annual'];
$subject = $_POST['subject'];
//$session = isset($_POST['session']) ? $_POST['session'] : "";//ternary operator
if(isset($_POST['session'])){
  $session = $_POST['session'];
} else {
  $session = "";
}
$result = "";
$first = "";
$last = "";
$sql = 'INSERT INTO halbForm SET 
    exam = :exam,
    year = :year,
  subject = :subject,
  session = :session,
  result = :result,
    first = :first,
    last = :last';
            $s = $pdo->prepare($sql);
            $s->bindParam(':exam', $exam);
            $s->bindParam(':year', $year);
            $s->bindParam(':subject', $subject);
            $s->bindParam(':session', $session);
            $s->bindParam(':result', $result);
            $s->bindParam(':first', $first);
            $s->bindParam(':last', $last);

Outside your loop. The loop should contain the following:

for ($i = 0; $i <= $j; $i++) {
    $result = $_POST['result' . $i];
    $first = $_POST['first' . $i];
    $last = $_POST['last' . $i];
    $s->execute();
  }

(Assuming you choose not to clean up your form. If you do, the loop looks like:

foreach ($_POST['result'] AS $key => $result) {
    $first = $_POST['first'][$key];
    $last = $_POST['last'][$key];
    $s->execute();
  }

5: SANITIZE YOUR DATA. Using unfiltered $_POST values is highly insecure.
6: A failed query does not (by default) throw a PDOException. Check $pdo->errorInfo.
[1]: http://php.net/manual/en/language.operators.precedence.php

1 Like

Hi,
The issue was that NULL was not allowed in the DB for that column.
All works now.
Thanks

Ok got that.

Yes I know I should do it with an array, just seemed simpler the way I did it.

Here ‘session’ comes from a selection menu, but next I will be using a checkbox menu for session in a search form section of the site. So this is good advice.

Ok how do I filter $_POST?

Ok will do.
Thanks

Yes of course I know what you mean by this. I need to use something like this,

<?php
function html($text)
{
  return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

function htmlout($text)
{
  echo html($text);
}

function markdown2html($text)
{
  $text = html($text);

  // strong emphasis
  $text = preg_replace('/__(.+?)__/s', '<strong>$1</strong>', $text);
  $text = preg_replace('/\*\*(.+?)\*\*/s', '<strong>$1</strong>', $text);

  // emphasis
  $text = preg_replace('/_([^_]+)_/', '<em>$1</em>', $text);
  $text = preg_replace('/\*([^\*]+)\*/', '<em>$1</em>', $text);

  // Convert Windows (\r\n) to Unix (\n)
  $text = str_replace("\r\n", "\n", $text);
  // Convert Macintosh (\r) to Unix (\n)
  $text = str_replace("\r", "\n", $text);

  // Paragraphs
  $text = '<p>' . str_replace("\n\n", '</p><p>', $text) . '</p>';
  // Line breaks
  $text = str_replace("\n", '<br>', $text);

  // [linked text](link URL)
  $text = preg_replace(
      '/\[([^\]]+)]\(([-a-z0-9._~:\/?#@!$&\'()*+,;=%]+)\)/i',
      '<a href="$2">$1</a>', $text);

  return $text;
}

function markdownout($text)
{
  echo markdown2html($text);
}

Thanks,

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.