multipart-message nevyn bengtsson's blog

featured articles 🦄, about, archive, tags

Lazy Man's Logging

file_put_contents(…, FILE_APPEND) to log is a bad idea and you know it, but it’s sometimes good enough, or you just don’t get paid enough to make something serious. I just let you make it a tiny bit more serious, a whole lot more dependable, and still just change a single line of code.
  /// Creates a table called $table as (id, when, message) if none such exists, and inserts a row with $message in it.
  /// If no connection details are given, it uses the current database connection. Same goes for $database and $when.
  ///
  /// @returns TRUE on success or FALSE on failure.
  ///
  /// @example mysql_put_contents("orders", "I CAN HAZ CHEEZBURGER?", "mysite", NULL, "127.0.0.1:3306", "mysite_user", "secret") or die(mysql_error());
  /// @example mysql_put_contents("guestbook", "Longcat says: I'm loooooooooooong") or die("Errorz!");
  function mysql_put_contents($table, $message, $database = NULL, $when = NULL, $host = NULL, $user = NULL, $pass = NULL) {
    if($host)
	    mysql_connect($host, $user, $pass);
	  if($database)
	    mysql_select_db($database);
	
	  $qry = "CREATE TABLE IF NOT EXISTS `$table` (
             `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
             `when` TIMESTAMP DEFAULT NOW(),
             `message` TEXT NOT NULL
           );";
    $result = mysql_query($qry);
    if($result === FALSE)
      return FALSE;
      
    $qry = "INSERT INTO `$table` VALUES(NULL, ".($when ? $when : 'NULL').", '".mysql_real_escape_string($message)."');";

    $result = mysql_query($qry);
    if($result === FALSE)
      return FALSE;
      
    return TRUE;
  }
	

Tagged coding, php, faves