Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

PHP Forum


You are currently viewing our PHP Forum as a guest. Please register to participate.
Login



Freelance Jobs

Reply
Converting a function to an object oriented approach
Old 07-06-2008, 10:35 PM Converting a function to an object oriented approach
Inet411's Avatar
Skilled Talker

Posts: 88
Name: programmer
Location: internet
Trades: 0
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
          
$valuestrim($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.
__________________

Please login or register to view this content. Registration is FREE

Inet411 is offline
Reply With Quote
View Public Profile Visit Inet411's homepage!
 
 
Register now for full access!
Old 07-07-2008, 10:45 PM Re: Converting a function to an object oriented approach
JeremyMiller's Avatar
WT Moderator

Posts: 1,712
Name: Jeremy Miller
Location: Las Vegas, NV
Trades: 0
This ought to get you started:

PHP Code:
<?php
class MySQLAuto {
  private 
$database_columns = array();
  public function 
__construct() {
    
/*
      Load data about the database tables.
      Better to load now, so that we load once.
      Better idea is to cache these results as they change very infrequently (e.g. save to a file as a serialized array)
    */

    
if ($current_tables mysql_query("SHOW TABLES")) {
      if (
mysql_num_rows($current_tables) > 0) {
        while (
$a_table mysql_fetch_assoc($current_tables)) {
          
$table_name current($a_table);
          
//Get columns for this table.
          
if ($table_columns $database->query("SHOW COLUMNS FROM ".$table_name)) {
            
$inline '';
            while (
$a_column msyql_fetch_assoc($table_columns)) {
              
$this->database_columns[$table_name][$a_column['Field']] = $a_column['Type'];
            }
          }
        }
      }
    }
  }
  public function 
autoSql($action$table_name$fields) {
    
$key_prefix ''$values_prefix '';
    switch (
$action) {
      case 
"insert":
        foreach(
$fields as $field_name=>$field_value) {
          if (isset(
$this->database_columns[$table_name][$field_name]) && !empty($field_value)) {
            
$key preg_replace('/[^a-z\_]/i','',$key); //Field names should only have a-z and _ in them.
            
$value $this->autoQuote($value); //values need to be quoted, where appropriate.
            
$keys .= $key_prefix.$key;
            
$values .= $values_prefix ;
            
$key_prefix ','$values_prefix ','//This makes it so you don't have to remove the trailing comma from results
          
}
        }

        if (
strlen($keys) > 0) {
          
//Only execute query if necessary (i.e. there are keys which implies there are values)
          
if ($res mysql_query("INSERT INTO ".$table_name." (".$keys.") VALUES (".$values.")")) {
            return 
mysql_insert_id();
          } else {
            
//Query failed, so return error.
            
return mysql_error();
          }
        }
        break;
      case 
'update':
        break;
      case 
'delete':
        break;
    }
    return -
1//No queries were executed!  Setting -1 as the error for failed query.
  
}
  private function 
autoQuote($value$add_quotes=true$allow_wildcards=true$require_quotes=false) {
    
// Taken from the PHP site, with modifications for quotes and wildcards.
    // Stripslashes
    
if (get_magic_quotes_gpc()) {
      
$value stripslashes($value);
    }
    
// Quote if not a number or a numeric string
    
if (is_numeric($value)) {
      if (
$require_quotes) {
        
$value "'" $value "'";
      }
    } else {
      if (
$add_quotes){
        
$value "'" mysql_real_escape_string($value) . "'";
      } else {
        
$value mysql_real_escape_string($value);
      }
    }
    if (!
$allow_wildcards) {
      
$value str_replace('%','\%',$value);
      
$value str_replace('_','\_',$value);
    }
    return 
$value;
  }
}
?>
__________________
Jeremy Miller

Please login or register to view this content. Registration is FREE
JeremyMiller is offline
Reply With Quote
View Public Profile Visit JeremyMiller's homepage!
 
Reply     « Reply to Converting a function to an object oriented approach
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 0.30414 seconds with 12 queries