-1

Possible Duplicate:
PHP file cannot enter some part of code

I am building a news website and I have a function file, for all functions but, nearly all the functions made the same way as the below example:

function one(){
$query  = "SELECT * FROM table WHERE id='$id'....";
$result = mysql_query($query);
while($row=mysql_num_rows($result))
{echo "$row[data]";}  }

So, basically there are many functions that serve different purpose, but have the same exact template as the above, So, to save time, codding I was thinking if is would be possible, to simplify the 5 lines? to one with function like:

function(something here, and here){then the result here?}

Since the only thing that may change from the first code are: Select, table names, id, and the $row[data], and everything will remain the same what if I assign those to variables and the rest structure will stay as it is in a function:

check this idea.

function simplify() {

$query = "$crud * FROM $table WHERE id= '$id' ";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)) {echo "$row[data]";}


} 

So anytime, I need to create the first code, I could just do

echo simlify(and here would be table name, id, select, create, update...) {

and here the result}

So sorry, for asking this complex question, or asking it with complexity but If anyone has any idea, about what I am talking about, I need your help.

Community
  • 1
  • 1
  • 1
    Have you tried ORM? http://stackoverflow.com/questions/108699/good-php-orm-library – Glavić Sep 29 '12 at 15:39
  • 1
    First of all drop the mysql functions and choose something with an object oriented interface that allows you to pass along result objects, like PDO or mysqli. Then wrap your find routines into class(es) of their own. No more `while`, only `foreach`. – hakre Sep 29 '12 at 15:44

1 Answers1

1

How about this, for a simple database call:

$db = new DBAdapter(array('host' => 'localhost'));
$results = $db->Select('mytable')->Where('id > 2')->Execute();

You can achieve this by building your own database class. Put the class in a separate file and reuse it many times.

class DBAdapter extends PDO
{
  public function __construct( array $params)
  {
     // construct the connection
  }

  public function Select ($table)
  {
    // do stuff for a table select
    return $this;
  }

  public function Count ($table)
  {
    // do stuff for a table count
    return $this;
  }


  public function Where ($condition)
  {
    // do stuff for a where
    return $this;
  }

  public function Execute ()
  {
    // execute stuff
    return $result;
  }
}
JvdBerg
  • 21,777
  • 8
  • 38
  • 55
  • Thank you but, that is PDO. I am starting to teach myself PDO so that code will come in handy after weeks or months. – samayo Oct 07 '12 at 21:39