Jump to content

If field is empty, insert value


spanster90

Recommended Posts

start with a query to grab the username row, then check if it is empty, then replace the empty field with the value Anonymous

$query = mysql_query("SELECT username from table_name WHERE column_name = column_name") or die(mysql_error());
$row = mysql_fetch_array($query);
   if($row['username'] == '')
   {
      $result = mysql_query(UPDATE table_name SET username = 'Anonymous' WHERE coulumn_name = column_name) or die(mysql_error());
   }

more simple:

mysql_query("UPDATE table_name SET username = 'Anonymous' WHERE username IS NULL OR username = '' ") 
                               or trigger_error('Update Failed : ' . mysql_error(), E_USER_ERROR);

 

just one query... no need to select the records first.

 

if you only use PhpMyAdmin run the provided UPDATE in a SQL tab.

 

you can also alter the table and define 'Anonymous' as the DEFAULT value for that field, in that way you don't need to run the UPDATE every time that a new record is inserted with that field null.

more simple:

mysql_query("UPDATE table_name SET username = 'Anonymous' WHERE username IS NULL OR username = '' ") 
                               or trigger_error('Update Failed : ' . mysql_error(), E_USER_ERROR);

 

just one query... no need to select the records first.

 

if you only use PhpMyAdmin run the provided UPDATE in a SQL tab.

 

you can also alter the table and define 'Anonymous' as the DEFAULT value for that field, in that way you don't need to run the UPDATE every time that a new record is inserted with that field null.

nice, didnt think of that

you can also alter the table and define 'Anonymous' as the DEFAULT value for that field, in that way you don't need to run the UPDATE every time that a new record is inserted with that field null.

 

I indeed tried this. I set it As Defined: Anonymous but I have scripts that insert to this database and when nothing is inserted to this field, it still shows up empty rather than Anonymous.

 

The scripts work great by the way in cron. I would just prefer the default method, is there a setting I'm missing?

Sql:

ALTER TABLE  `table_name` CHANGE  `first_name`  `first_name` CHAR( 15 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT  'Anonymous'

 

otherwise go to the field you want to change in myAdmin, and click edit, In there set the default to Anonymous. Now when ever something gets put in there when the name column is not specified in the query it will default to the default value.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.