Page 1 of 1

Replace blank $_POST value with NULL

Posted: Sat Aug 04, 2007 2:35 am
by SkyFlyer
Hi.... I have a question and I can't seem to figure it out.

I would consider myself to be between the beginner and intermediate levels of PHP programming. I haven't coded in PHP for a year or two now, except for the past two weeks.

I am pulling data from a HTML form... we'll say the field is called "phone", along with fields 1, 2, etc

I want to insert this data into mysql database people table contact.

After the connection info, I have

Code: Select all

$sql="INSERT INTO contact (phone, 1, 2, etc)
VALUES
('$_POST[phone]', '$_POSt[1]', '$_POST[2]', '$_POST[etc]')";
Lets say field phone is left empty on the HTML form, and I want empty forms turned into cells with value NULL in mysql.

What type of if statement would I have php run to verify that the length of a field is > 0, and if it isn't, change '$_POST[field]' to NULL

??

Thanks.

Posted: Sat Aug 04, 2007 3:51 am
by Chris Corbyn
What you're currently doing is extremely dangerous. Read up on SQL injection attacks.

Code: Select all

$sql_vars = array();
foreach ($_POST as $k => $v)
{
  if (empty($v))
  {
    $sql_vars[$k] = "NULL";
  }
  else
  {
    $sql_vars[$k] = "'" . mysql_real_escape_string($v) . "'";
  }
}

Code: Select all

$sql="INSERT INTO contact (phone, 1, 2, etc) 
VALUES 
($sql_vars[phone], $sql_vars[1], $sql_vars[2], $sql_vars[etc])";

Posted: Sat Aug 04, 2007 3:57 am
by SkyFlyer
d11wtq wrote:What you're currently doing is extremely dangerous. Read up on SQL injection attacks.

Code: Select all

$sql_vars = array();
foreach ($_POST as $k => $v)
{
  if (empty($v))
  {
    $sql_vars[$k] = "NULL";
  }
  else
  {
    $sql_vars[$k] = "'" . mysql_real_escape_string($v) . "'";
  }
}

Code: Select all

$sql="INSERT INTO contact (phone, 1, 2, etc) 
VALUES 
($sql_vars[phone], $sql_vars[1], $sql_vars[2], $sql_vars[etc])";
Thanks, I will give that a shot.

And yes, I know that this script would normally be very unsecure.

However, the only people who will use or access it will be behind a secure network accessing a database behind the same network.

I'm just writing this to save time so they don't have to write a couple hundred insert statements. :)

Posted: Sat Aug 04, 2007 4:06 am
by SkyFlyer
Nicely done. Thanks mate.

Major kudos. :)

Now, one table down, 8 more to go. :P

Posted: Sat Aug 04, 2007 4:06 am
by s.dot
Your database table can be changed to set fields to NULL if they are empty.

Posted: Sat Aug 04, 2007 4:26 am
by SkyFlyer
scottayy wrote:Your database table can be changed to set fields to NULL if they are empty.
Yup, but I'm not the one who set up the table structure. I'd rather not mess with it. Don't know their reasons for making it that way, and I don't really care either. :) Thanks to d11wtq I have the best of both worlds. :)