If anyone has any ideas on converting this to a class... any help would be great.
//brief explanation:
//the function gets all the fields from the table name entered in the function.
//compares them to the names in the sqlArray entered in the function.
//then inserts the values of the sqlArray into the appropriate fields in the table.
//
PHP Code:
function doSql($do_what,$tablename,$sqlArray) {
switch ($do_what) {
case "insert":
$res = mysql_query("SHOW COLUMNS FROM ".$tablename);
while($blah = mysql_fetch_array($res)) {
$fields[]=$blah[0];
}
foreach($sqlArray as $key=>$value) {
if (in_array($key,$fields) && $value !='') {
$key=mysql_real_escape_string($key);
$value=mysql_real_escape_string($value);
$keys.="$key,";
$values.="'$value',";
}
}
$keys = trim($keys,","); //strips the last comma
$values= trim($values,","); //strips the last comma
$res = mysql_query("INSERT INTO $tablename ($keys) VALUES ($values)");
return mysql_insert_id();
break;
}
Sample usage:
PHP Code:
doSql("insert","content",$_POST);
insert = do what? meaning (insert into db, update db, delete from etc..)
content = the table name
$_POST = an array of everything to be inserted.
The form is this:
<form method='post'>
<input type='hidden' name = 'content_id' value = '4'>
<input type='text' name = 'article_name' value = 'an-article'>
<input type='text' name = 'category' value = 'php'>
<input type='text' name = 'date' value = '2008-01-01'>
<input type='submit' name = 'submit' value = 'submit'>
</form>
So when the form is submitted the key - values are content_id=>4,article_name=an-article etc....
it automatically inserts each into the database and returns the id.
The function works exactly as I wanted it to. I could continue to extend it by making more functions inside this function but this gets unruly.
So now besides validation... how would I turn my function into an extendable class.