<?php

// This is a PHP-generating PHP script

// It generates code for a PHP class based on any arbitrary table schema

// It takes care of sets, gets, constructor, and persistence (saving to db)

// Usage:

// If you have a table called 'users' with columns 'id' and 'name'

// You would construct an object like $myUser = new User($id,$dbh);

// Then $myUser->set_name('new name');

// And $myUser->save();

$dbh = db_connect ( ) ;

$dbname = 'simp' ;

$class = 'user' ;

$table = 'users' ;

function getColumns ( $dbh , $dbname , $table ) {

$colsql = "select column_name from information_schema.columns where table_name=? AND table_schema=?" ;

$colres = $dbh -> prepare ( $colsql ) ;

$colres -> execute ( array ( $table , $dbname ) ) ;

while ( $colrow = $colres -> fetch ( ) ) {

$columns [ ] = $colrow [ 'column_name' ] ;

}

return $columns ;

}

$cols = getColumns ( $dbh , $dbname , $table ) ;

$output .= 'class ' . $class . ' {' ;

foreach ( $cols as $col ) {

$output .= 'private $' . $col . ';' ;

$output .= "function get_ $col (){" ;

$output .= 'return $this->' . $col . ';' ;

$output .= "}" ;

$output .= 'function set_' . $col . '($new_val){' ;

$output .= '$this->' . $col . ' = $new_val;' ;

$output .= "}" ;

}

$output .= 'function __construct($id,$dbh){' ;

$output .= '$q = "SELECT * FROM ' . $table . ' WHERE id=?";' ;

$output .= '$sth = $dbh->prepare($q);' ;

$output .= '$sth->execute(array($id));' ;

$output .= 'while($row = $sth->fetch()){' ;

foreach ( $cols as $col ) {

$output .= '$this->' . $col . ' = $row[\'' . $col . '\'];' ;

}

$output .= '}//endwhile' ;

$output .= '}//endconstructor' ;

$output .= 'function save(){' ;

$output .= '$id = $this->id;' ;

$output .= '$dbh = $this->dbh;' ;

foreach ( $cols as $col ) {

$output .= '$col = $this->' . $col . ';' ;

$output .= '$q = "UPDATE ' . $table . ' SET ' . $col . '=? WHERE id=?";' ;

$output .= '$sth = $dbh->prepare($q);' ;

$output .= '$sth->execute(array($col,$id));' ;

}

$output .= '}//endsave' ;

$output .= '}//endclass' ;

print $output ;