This is by no means the best way or even the way I would choose to do it, but it might serve as an example of how to modularize things more, keeping each method narrowly focused on serving a single "mission" in the scheme of things. It also demonstrates how you could make use of the __set() "magic" method, just for the fun of it. Hopefully this will give you some ideas and lead you to some more things to think about.
<?php
class newrecord
{
// Variables
private $tbl_name;
private $fields = array(
'postid' => null,
'subject' => null,
'body' => null,
'date' => null,
'poster' => null
);
/**
* Set the table name
* @param string $name
* @return bool
*/
public function set_tbl_name($name)
{
$this->tbl_name = trim($name);
return (bool)$this->tbl_name; // false if set to empty string
}
/**
* Set $fields values
* Uses the __set() "magic" method
* @param string $key
* @param mixed $value
* @return bool
*/
public function __set($key, $value)
{
if(array_key_exists($key, $this->fields))
{
$this->fields[$key] = trim($value);
return true;
}
else
{
user_error("Invalid field '$key'");
return false;
}
}
/**
* Do the insert
* @return bool
*/
public function PostToDatabase()
{
$sql = $this->MakeSQL();
$query = mysql_query($sql);
if(!$query)
{
error_log(mysql_error()."\n$sql");
}
return (bool)$query;
}
/**
* Create insert SQL string
* @return string
*/
private function MakeSQL()
{
$sql = sprintf(
"INSERT INTO `%s` (`%s`) VALUES(%s)",
$this->tbl_name,
$this->field_list(),
$this->value_list()
);
return $sql;
}
/**
* Create list of fields for use in SQL
* @return string
*/
private function field_list()
{
$fields = array();
foreach($this->fields as $key => $val)
{
$fields[] = "`$key`";
}
return implode(',', $fields);
}
/**
* Create list of values for use in insert SQL
* @return string
*/
private function value_list()
{
$values = array();
foreach($this->fields as $value)
{
if(is_numeric($value))
{
$values[] = $value;
}
else
{
$values[] = "'".mysql_real_escape_string($value)."'";
}
}
return implode(',', $values);
}
}
Sample usage:
<?php
require_once 'newrecord.php';
mysql_connect('localhost', 'foo', 'bar');
$test = new newrecord();
$test->set_tbl_name('test');
$test->subject = 'test subject'; // uses "magic" __set() method -- cool, eh?
$test->body = 'test body';
// etc. for other fields
$test->PostToDatabase();