Skip to content

Instantly share code, notes, and snippets.

@chrisledet
Last active June 21, 2018 00:25
Show Gist options
  • Save chrisledet/1608704 to your computer and use it in GitHub Desktop.
Save chrisledet/1608704 to your computer and use it in GitHub Desktop.
ActiveRecord written in PHP (written in 2008)
<?php
include_once "database.php";
class ActiveRecord
{
private $table = '';
private $table_contents = array();
private $primary_key = "id";
public $ONE_TO_ONE = 1;
public $ONE_TO_MANY = 2;
public $MANY_TO_MANY = 3;
public function __construct($pkey = "") {
$this->table = get_class($this);
$this->table = strtolower($this->table);
$this->table = $this->table."s";
$this->mapColumns();
if(isset($pkey)) {
$this->mapSelf($pkey);
}
}
private final function mapColumns() {
$query = "show columns from $this->table";
$result = mysql_query($query);
if($result) {
while ($row = mysql_fetch_assoc($result)) {
$field_name = $row['Field'];
$this->table_contents[$field_name] = "";
}
} else {
echo mysql_error()."\n";
}
}
private final function mapSelf($pkey) {
// echo "getting info from $this->table<br />";
$query = "select * from $this->table where $this->primary_key = '$pkey';";
$result = mysql_query($query);
if($result) {
$row = mysql_fetch_assoc($result);
$cols = $this->getFields();
foreach($cols as $field) {
$val = $row[$field];
// echo "setting $field to $val<br />";
$this->set($field, $row[$field]);
}
}
}
public function getFields() {
/* returns an array of the indexes of the array 'fields' */
return array_keys($this->table_contents);
}
/* returns array of each row in record */
public function to_a() {
$table_contents = $this->getFields();
$values = array();
foreach($table_contents as $field) {
$values[] = $this->get($field);
}
return $values;
}
public function save() {
if($this->isNewRecord()) {
// echo "inserting!!";
return $this->insertRecord();
} else {
// echo "updating!!";
return $this->updateRecord();
}
}
private function insertRecord() {
$next_pk = $this->nextPrimaryKey();
$this->set($this->primary_key, $next_pk);
$table_contents_str = implode(', ', array_map('mysql_escape_string', array_keys($this->table_contents)));
$vals_str = implode('", "', array_map('mysql_escape_string', $this->table_contents));
$insert_query = "INSERT INTO $this->table ($table_contents_str) VALUES (\"$vals_str\")";
//echo "$insert_query<br />";
$result = mysql_query($insert_query);
//echo "results: ".$result;
if($result) {
return true;
} else {
return false;
}
}
public function delete() {
$pkey = $this->get($this->primary_key);
$query = "delete from $this->table where $this->primary_key = '$pkey';";
$result = mysql_query($query);
if ($result) {
return true;
} else {
die("Error when deleting!");
}
}
private function updateRecord() {
$pkey = $this->get($this->primary_key);
$set_fields = " set ";
$keys = array_keys($this->table_contents);
$lastkey = end($keys);
foreach($keys as $key) {
if($key === $this->primary_key) { continue; }
$val = $this->table_contents[$key];
$set_fields = $set_fields."$key = '$val'".($key == $lastkey ? "" : ", ");
}
$update_query = "update $this->table $set_fields where $this->primary_key = '$pkey';";
$result = mysql_query($update_query);
return ($result ? true : false);
}
private function nextPrimaryKey() {
$query = "SHOW TABLE STATUS LIKE '$this->table'";
$result = mysql_query($query);
if ($result && mysql_num_rows($result)) {
$row = mysql_fetch_assoc($result);
return $row["Auto_increment"];
} else {
die("error retrieving next primary key!");
}
}
public function isNewRecord() {
return !(isset($this->table_contents[$this->primary_key]));
}
public function to_s() {
print_r($this->table_contents);
}
public function setId($pkey) {
$this->mapSelf($pkey);
}
public function set($field_name, $field_value) {
$this->table_contents[$field_name] = $field_value;
}
public function get($field_name) {
return $this->table_contents[$field_name];
}
public final function getTable() {
return $this->table;
}
protected function setPrimaryKey($pkey) {
$this->primary_key = $pkey;
}
public function getType($child_class, $relationship, $options = "") {
/* $child_class has to be an ActiveRecord child */
if($relationship == 1) {
$child = new $child_class;
$tbl_name = $child->get_table_name();
// echo "tbl_name = $tbl_name<br />";
$child_id_name = $this->singular($tbl_name)."_id";
// echo "child_id_name = $child_id_name<br />";
$child_id = $this->get($child_id_name);
// echo "child_id = $child_id<br />";
$child->setId($child_id);
// echo "child_class = ".$child->to_s()."<br />";
return $child;
}
else {
echo "error in getType($child_class, $relationship, $options)";
}
}
public function singular($haystack) {
/* TODO - Fix this shit! -- works but it's ugly!!! */
$last = strrpos($haystack, "s");
return ($last ? substr_replace($haystack, "", $last) : $haystack);
}
public function search($data) {
/* format of $data : [:column_name => 'value', :column_name1 => [1,2,3] ] */
$sql = 'select id from '.$this->get_table_name().' where ';
$cond = '';
if($data) {
$columns_to_search = array_keys($data);
$first_column = $columns_to_search[0];
$last_column = end($columns_to_search);
foreach($columns_to_search as $col) {
if(is_array($data[$col])) {
$vals = implode(',', $data[$col]);
$cond = $cond."$col in (".$vals.')';
} else {
$cond = $cond."$col like "."'%".$data[$col]."%'";
}
/* if not last column */
if($last_column != $col) {
$cond = $cond.' and ';
}
} // end of foreach
} // end of if($data)
$sql = $sql.$cond;
// echo '<b>SQL:</b>'.$sql;
$mysql_results = mysql_query($sql);
if($mysql_results) {
$search_results = array();
$x = 0;
while($row = mysql_fetch_assoc($mysql_results)) {
$sub_class = get_class($this);
$new_record = new $sub_class;
$new_record->setId($row[$this->primary_key]);
$search_results[$x] = $new_record;
$x++;
}
return $search_results;
}
}
public function findDistinctValues($column_name) {
/* returns an array of strings */
$result = mysql_query("select distinct $column_name from $this->table;");
if($result) {
$values = array();
while($row = mysql_fetch_assoc($result)) {
$values[] = $row[$column_name];
}
return $values;
}
else {
echo "Can not retrieve distinct columns of $column_name!";
}
}
public function findCount($conditions) {
$result = mysql_query("select count(*) as num from $this->table where $condition;");
if($result) {
while($row = mysql_fetch_assoc($result)) {
$num = $row['num'];
}
}
return $num;
}
public function findAll($condition = "") {
$result = mysql_query("select $this->primary_key from $this->table $condition;");
if($result) {
$collection = array();
$x = 0;
while($row = mysql_fetch_assoc($result)) {
$sub_class = get_class($this);
$new_record = new $sub_class;
$new_record->setId($row[$this->primary_key]);
$collection[$x] = $new_record;
$x++;
}
return $collection;
}
else {
// echo "Error retrieving records!";
}
}
public function get_table_name() {
return $this->table;
}
public function findByCondition($cond = "") {
$sql = "select id from $this->table where $cond;";
//echo "sql = $sql";
$result = mysql_query($sql);
if($result) {
$collection = array();
$x = 0;
while($row = mysql_fetch_assoc($result)) {
$sub_class = get_class($this);
$new_record = new $sub_class;
$new_record->setId($row['id']);
$collection[$x] = $new_record;
$x++;
}
return $collection;
}
else {
echo "Can not retrieve records by $cond";
}
}
public function findBy($field, $value, $cond = "") {
$sql = "select id from $this->table where $field = '$value' $cond";
// echo "sql = $sql";
$result = mysql_query($sql);
if($result) {
$collection = array();
$x = 0;
while($row = mysql_fetch_assoc($result)) {
$sub_class = get_class($this);
$new_record = new $sub_class;
$new_record->setId($row['id']);
$collection[$x] = $new_record;
$x++;
}
return $collection;
}
else {
echo "Can not retrieve records by $field = $value!";
}
}
}
?><?php
include_once "database.php";
class ActiveRecord
{
private $table = '';
private $table_contents = array();
private $primary_key = "id";
public $ONE_TO_ONE = 1;
public $ONE_TO_MANY = 2;
public $MANY_TO_MANY = 3;
public function __construct($pkey = "") {
$this->table = get_class($this);
$this->table = strtolower($this->table);
$this->table = $this->table."s";
$this->mapColumns();
if(isset($pkey)) {
$this->mapSelf($pkey);
}
}
private final function mapColumns() {
$query = "show columns from $this->table";
$result = mysql_query($query);
if($result) {
while ($row = mysql_fetch_assoc($result)) {
$field_name = $row['Field'];
$this->table_contents[$field_name] = "";
}
} else {
echo mysql_error()."\n";
}
}
private final function mapSelf($pkey) {
// echo "getting info from $this->table<br />";
$query = "select * from $this->table where $this->primary_key = '$pkey';";
$result = mysql_query($query);
if($result) {
$row = mysql_fetch_assoc($result);
$cols = $this->getFields();
foreach($cols as $field) {
$val = $row[$field];
// echo "setting $field to $val<br />";
$this->set($field, $row[$field]);
}
}
}
public function getFields() {
/* returns an array of the indexes of the array 'fields' */
return array_keys($this->table_contents);
}
/* returns array of each row in record */
public function to_a() {
$table_contents = $this->getFields();
$values = array();
foreach($table_contents as $field) {
$values[] = $this->get($field);
}
return $values;
}
public function save() {
if($this->isNewRecord()) {
// echo "inserting!!";
return $this->insertRecord();
} else {
// echo "updating!!";
return $this->updateRecord();
}
}
private function insertRecord() {
$next_pk = $this->nextPrimaryKey();
$this->set($this->primary_key, $next_pk);
$table_contents_str = implode(', ', array_map('mysql_escape_string', array_keys($this->table_contents)));
$vals_str = implode('", "', array_map('mysql_escape_string', $this->table_contents));
$insert_query = "INSERT INTO $this->table ($table_contents_str) VALUES (\"$vals_str\")";
//echo "$insert_query<br />";
$result = mysql_query($insert_query);
//echo "results: ".$result;
if($result) {
return true;
} else {
return false;
}
}
public function delete() {
$pkey = $this->get($this->primary_key);
$query = "delete from $this->table where $this->primary_key = '$pkey';";
$result = mysql_query($query);
if ($result) {
return true;
} else {
die("Error when deleting!");
}
}
private function updateRecord() {
$pkey = $this->get($this->primary_key);
$set_fields = " set ";
$keys = array_keys($this->table_contents);
$lastkey = end($keys);
foreach($keys as $key) {
if($key === $this->primary_key) { continue; }
$val = $this->table_contents[$key];
$set_fields = $set_fields."$key = '$val'".($key == $lastkey ? "" : ", ");
}
$update_query = "update $this->table $set_fields where $this->primary_key = '$pkey';";
$result = mysql_query($update_query);
return ($result ? true : false);
}
private function nextPrimaryKey() {
$query = "SHOW TABLE STATUS LIKE '$this->table'";
$result = mysql_query($query);
if ($result && mysql_num_rows($result)) {
$row = mysql_fetch_assoc($result);
return $row["Auto_increment"];
} else {
die("error retrieving next primary key!");
}
}
public function isNewRecord() {
return !(isset($this->table_contents[$this->primary_key]));
}
public function to_s() {
print_r($this->table_contents);
}
public function setId($pkey) {
$this->mapSelf($pkey);
}
public function set($field_name, $field_value) {
$this->table_contents[$field_name] = $field_value;
}
public function get($field_name) {
return $this->table_contents[$field_name];
}
public final function getTable() {
return $this->table;
}
protected function setPrimaryKey($pkey) {
$this->primary_key = $pkey;
}
public function getType($child_class, $relationship, $options = "") {
/* $child_class has to be an ActiveRecord child */
if($relationship == 1) {
$child = new $child_class;
$tbl_name = $child->get_table_name();
// echo "tbl_name = $tbl_name<br />";
$child_id_name = $this->singular($tbl_name)."_id";
// echo "child_id_name = $child_id_name<br />";
$child_id = $this->get($child_id_name);
// echo "child_id = $child_id<br />";
$child->setId($child_id);
// echo "child_class = ".$child->to_s()."<br />";
return $child;
}
else {
echo "error in getType($child_class, $relationship, $options)";
}
}
public function singular($haystack) {
/* TODO - Fix this shit! -- works but it's ugly!!! */
$last = strrpos($haystack, "s");
return ($last ? substr_replace($haystack, "", $last) : $haystack);
}
public function search($data) {
/* format of $data : [:column_name => 'value', :column_name1 => [1,2,3] ] */
$sql = 'select id from '.$this->get_table_name().' where ';
$cond = '';
if($data) {
$columns_to_search = array_keys($data);
$first_column = $columns_to_search[0];
$last_column = end($columns_to_search);
foreach($columns_to_search as $col) {
if(is_array($data[$col])) {
$vals = implode(',', $data[$col]);
$cond = $cond."$col in (".$vals.')';
} else {
$cond = $cond."$col like "."'%".$data[$col]."%'";
}
/* if not last column */
if($last_column != $col) {
$cond = $cond.' and ';
}
} // end of foreach
} // end of if($data)
$sql = $sql.$cond;
// echo '<b>SQL:</b>'.$sql;
$mysql_results = mysql_query($sql);
if($mysql_results) {
$search_results = array();
$x = 0;
while($row = mysql_fetch_assoc($mysql_results)) {
$sub_class = get_class($this);
$new_record = new $sub_class;
$new_record->setId($row[$this->primary_key]);
$search_results[$x] = $new_record;
$x++;
}
return $search_results;
}
}
public function findDistinctValues($column_name) {
/* returns an array of strings */
$result = mysql_query("select distinct $column_name from $this->table;");
if($result) {
$values = array();
while($row = mysql_fetch_assoc($result)) {
$values[] = $row[$column_name];
}
return $values;
}
else {
echo "Can not retrieve distinct columns of $column_name!";
}
}
public function findCount($conditions) {
$result = mysql_query("select count(*) as num from $this->table where $condition;");
if($result) {
while($row = mysql_fetch_assoc($result)) {
$num = $row['num'];
}
}
return $num;
}
public function findAll($condition = "") {
$result = mysql_query("select $this->primary_key from $this->table $condition;");
if($result) {
$collection = array();
$x = 0;
while($row = mysql_fetch_assoc($result)) {
$sub_class = get_class($this);
$new_record = new $sub_class;
$new_record->setId($row[$this->primary_key]);
$collection[$x] = $new_record;
$x++;
}
return $collection;
}
else {
// echo "Error retrieving records!";
}
}
public function get_table_name() {
return $this->table;
}
public function findByCondition($cond = "") {
$sql = "select id from $this->table where $cond;";
//echo "sql = $sql";
$result = mysql_query($sql);
if($result) {
$collection = array();
$x = 0;
while($row = mysql_fetch_assoc($result)) {
$sub_class = get_class($this);
$new_record = new $sub_class;
$new_record->setId($row['id']);
$collection[$x] = $new_record;
$x++;
}
return $collection;
}
else {
echo "Can not retrieve records by $cond";
}
}
public function findBy($field, $value, $cond = "") {
$sql = "select id from $this->table where $field = '$value' $cond";
// echo "sql = $sql";
$result = mysql_query($sql);
if($result) {
$collection = array();
$x = 0;
while($row = mysql_fetch_assoc($result)) {
$sub_class = get_class($this);
$new_record = new $sub_class;
$new_record->setId($row['id']);
$collection[$x] = $new_record;
$x++;
}
return $collection;
}
else {
echo "Can not retrieve records by $field = $value!";
}
}
}
?>
@chrisledet
Copy link
Author

I wrote this long time ago for a project that I was forced to use PHP on. I was very naive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment