Jump to content

Insert predefined value into MySQL if form is empty

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
Trufa

Trufa

    Newbie

  • Members
  • Pip
  • 8 posts
Hi guys, I wanted to know how can i do the following.

This code is correctly inserting into the MySQL table.

The thing is i want to be able to leave the "name" empty in the form and (if that were the case) "Anonymous" should be inserted into the name filed.

<?php

$con = mysql_connect("localhost","root","root");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }


mysql_select_db("jacket", $con);


$sql="INSERT INTO quote (frase, name)

VALUES

('$_POST[frase]','$_POST[name]')";


if (!mysql_query($sql,$con))

  {

  die('Error: ' . mysql_error());

  }

echo "Thanks? Insult submited";


mysql_close($con)

?>

I dont know wether the question is sufficiently clear, if not please ask me!!

Thanks in advance

Juan

#2
Calgon

Calgon

    Learning Programmer

  • Members
  • PipPipPip
  • 56 posts
The code below checks the length of the posted 'name' string, if the length returned is 0, then the code will insert 'Anonymous' instead of the name variable. Enjoy.


if(strlen($_POST[name]) == 0) {

	$sql = "INSERT INTO quote (frase, name) VALUES ('$_POST[frase]','Anonymous')";

} 

else {

	$sql = "INSERT INTO quote (frase, name) VALUES ('$_POST[frase]', '$_POST[name]')";

}