meong_garongAvatar border
TS
meong_garong
permisi suhu dan mastah sekalian saya seoranh nubitol dalam web design dan programing
permisi suhu dan mastah sekalian
saya seoranh nubitol dalam web design dan programing emoticon-Malu
saya mohon bantuan mastah sekalian untuk membantu ane, ane bingung emoticon-Bingung
gimana caranya menjoin table yg berbeda dalam php pdo emoticon-Matabelo

posts.php

<?php
session_start();
require_once 'library/DatabaseObject.php';
require_once 'library/Db_Select.php';
require_once 'model/Post.php';
require_once 'model/Comment.php';
require_once 'inc/functions.php';

$post = new Post();
$comment = new Comment();

$limit = 10;
$records = $limit;
$show_more_button = 0;

switch($_GET['home']){
case 'add':
// save
$post->name = $_SESSION['fname'].' '.$_SESSION['lname'];
$post->post = checkValues($_POST['post']);
$post->users_id = $_SESSION['userid'];
$post->date_created = strtotime(date("Y-m-d H:i:s"));
$post->save();

// setelah save tampilkan limit 1
$select = $post->select();
$select->from('posts', array('*', 'UNIX_TIMESTAMP() - date_created AS CommentTimeSpent'));
$select->order('posts_id', 'DESC');
$select->limit(0, 1);
$posts = $post->fetchObj($select);

break;

case 'more':
$show = $_POST['show'];
$records = $show + $limit;

// select
$select = $post->select();
$select->from('posts', array('*', 'UNIX_TIMESTAMP() - date_created AS CommentTimeSpent'));
$select->order('posts_id', 'DESC');
$select->limit($show, $limit);
$posts = $post->fetchObj($select);

// masih lebih ?
$select = $post->select();
$select->from('posts');
$select->limit($records, $limit);
$check_result = count($post->fetchObj($select));

if($check_result > 0)
$show_more_button = 1;
break;

default:
$select = $post->select();
$select->from('posts', array('*', 'UNIX_TIMESTAMP() - date_created AS CommentTimeSpent'));
$c = $post->fetchObj($select);

$select->limit(0, $limit);
$select->order('posts_id', 'DESC');
$posts = $post->fetchObj($select);

if((count($c)) > $limit)
$show_more_button = 1;
break;
}

foreach ($posts as $row): ?>
<div class="friends_area" id="record-<?php echo $row->posts_id; ?>">
<img src="images/avatar-post.png" class="alignleft" alt="" />
<label class="alignleft name">
<a >users_id; ?>"><b><?php echo ucwords($row->name);?></b></a>
<em><?php echo $row->post;?></em>

<br clear="all" />

<span><?php echo getTime($row->CommentTimeSpent, $row->date_created); ?></span>
<a href="[removed]void(0)">posts_id ?>" class="showCommentBox">Komentar</a>
</label>
<?php
$users_id = $_SESSION['userid'];
if($row->users_id == $users_id):?>
<a href="[removed]void(0);" class="delete">Hapus</a>
<?php endif; ?>
<br/>

<br clear="all" />

<div id="CommentPosted<?php echo $row->posts_id ?>">
<?php
$select_c = $comment->select();
$select_c->from('comments', array('*', 'UNIX_TIMESTAMP() - date_created AS CommentTimeSpent'));
$select_c->where('posts_id = ?', $row->posts_id);
$select_c->order('comments_id', 'ASC');
$select_c->limit(0, 10);
$comments = $comment->fetchObj($select_c);

$comment_num_row = count($comments);
if($comment_num_row):
foreach ($comments as $rowC):?>
<div class="commentPanel" id="record-<?php echo $rowC->comments_id;?>" align="left">
<img src="images/avatar-comment.jpeg" width="40" class="alignleft CommentImg" alt="" />
<label class="postedComments">
<?php echo $rowC->comment;?>
<br clear="all" />
<span class="commentTime">
<?php echo getTime($rowC->CommentTimeSpent, $rowC->date_created); ?>
</span>
<?php
$users_id = $_SESSION['userid'];
if($rowC->users_id == $users_id):?>
  <a href="#">comments_id;?>" class="c_delete">Hapus</a>
<?php endif;?>
</label>
<br clear="all" />
</div>
<?php endforeach;?>
<?php
endif;?>
</div>
<div class="commentBox" align="right" id="commentBox-<?php echo $row->posts_id;?>" <?php echo (($comment_num_row) ? '' :'style="display:none"')?>>
<a >users_id; ?>"><img src="images/avatar-comment.jpeg" width="40" class="alignleft CommentImg" style="display:none" alt="" /></a>
<label id="record-<?php echo $row->posts_id;?>">
<textarea class="commentMark" id="commentMark-<?php echo $row->posts_id;?>" name="commentMark" cols="60"></textarea>
</label>
<br clear="all" />
<a id="SubmitComment" class="small button comment" style="display:none">Komen</a>
</div>
</div>
<?php
endforeach;

if($show_more_button == 1):?>
<div id="bottomMoreButton">
<a id="<?php echo $records?>" class="more_records" href="[removed] void(0)">Kiriman lama</a>
</div>
<?php endif; ?>


DatabaseObject.php

<?php
class DatabaseObject
{

const PDO_USERNAME = 'root'; //user DB MySQL
const PDO_PASSWORD = '17041987'; //password DB MySQL
const PDO_DBNAME = 'konkoow'; //DB name MySQL

const TYPE_TIMESTAMP = 1;
const TYPE_BOOLEAN = 2;

protected static $types = array(self::TYPE_TIMESTAMP, self::TYPE_BOOLEAN);

protected $_db = null;
protected $_table = '';
protected $_idField = '';

private $_id = null;
private $_properties = array();
private $bind = array();

public function __construct($table, $idField)
{
try
{
$this->_db = new PDO ('mysql:host=localhost;dbname=' . self::PDO_DBNAME, self::PDO_USERNAME, self::PDO_PASSWORD);
$this->_table = $table;
$this->_idField = $idField;
}
catch (PDOException $e)
{
print 'Kesalahan : '. $e->getMessage() . '<br/>';
die();
}
}

public function __set($name, $value)
{
if (array_key_exists($name, $this->_properties)) {
$this->_properties[$name]['value'] = $value;
$this->_properties[$name]['updated'] = true;
return true;
}

return false;
}

public function __get($name)
{
return array_key_exists($name, $this->_properties) ? $this->_properties[$name]['value'] : null;
}

protected function add($field, $default = null, $type = null)
{
$this->_properties[$field] = array('value' => $default,
'type' => in_array($type, self::$types) ? $type : null,
'updated' => false);
}

public function isSaved()
{
return $this->getId() > 0;
}

public function getId()
{
return (int) $this->_id;
}

public function clear()
{
return $this->_id = null;
}

public function getDb()
{
return $this->_db;
}

public function getTable()
{
return $this->_table;
}

public function lastInsertId()
{
return $this->id;
}

public function getBind()
{
return $this->bind;
}

public function clearBind()
{
unset($this->bind);
}

protected function getSelectFields($prefix = '')
{
$fields = array($prefix . $this->_idField);
foreach ($this->_properties as $k => $v)
$fields[] = $prefix . $k;

return $fields;
}

/*** LOGIC ***/

public function load($id, $field = null)
{
if (strlen($field) == 0)
$field = $this->_idField;

if ($field == $this->_idField) {
$id = (int) $id;
if ($id <= 0)
return false;
}

$query = sprintf('select %s from %s where %s = ?',
join(', ', $this->getSelectFields()),
$this->_table,
$field);

$query = $this->quote($query, $id);

return $this->_load($query, $id);
}

protected function _load($query, $id)
{
$result = $this->query($query);

$row = $result->fetch();
if (!$row)
return false;

$this->_init($row);

$this->postLoad();

return true;
}

public function _init($row)
{
foreach ($this->_properties as $k => $v)
{
$val = $row[$k];

switch ($v['type'])
{
case self::TYPE_TIMESTAMP:
if (!is_null($val))
$val = strtotime($val);
break;
case self::TYPE_BOOLEAN:
$val = (bool) $val;
break;
}

$this->_properties[$k]['value'] = $val;
}
$this->_id = (int) $row[$this->_idField];
}

public function save()
{
$update = $this->isSaved();

if ($update)
$commit = $this->preUpdate();
else
$commit = $this->preInsert();

if (!$commit) {
return false;
}

$row = array();

foreach ($this->_properties as $k => $v) {
if ($update && !$v['updated'])
continue;

switch ($v['type']) {
case self::TYPE_TIMESTAMP:
if (!is_null($v['value']))
$v['value'] = date('Y-m-d H:i:s', $v['value']);
break;

case self::TYPE_BOOLEAN:
$v['value'] = (int) ((bool) $v['value']);
break;
}

$row[$k] = $v['value'];
}

if (count($row) > 0) {
// perform insert/update
if ($update) {
$this->_update($this->_table, $row, sprintf('%s = %d', $this->_idField, $this->getId()));
}
else {
$this->_insert($this->_table, $row);
$this->_id = $this->_db->lastInsertId();
}
}

// update internal id

if ($commit) {
if ($update)
$commit = $this->postUpdate();
else
$commit = $this->postInsert();
}

return $commit;
}

public function delete()
{
if (!$this->isSaved())
return false;

$commit = $this->preDelete();

if ($commit)
$this->_delete($this->_table, sprintf('%s = %d', $this->_idField, $this->getId()));
else
return false;

$commit = $this->postDelete();

$this->clear();

return $commit;
}

/*** CALLBACK ***/

protected function preInsert()
{
return true;
}

protected function postInsert()
{
return true;
}

protected function preUpdate()
{
return true;
}

protected function postUpdate()
{
return true;
}

protected function preDelete()
{
return true;
}

protected function postDelete()
{
return true;
}

protected function postLoad()
{
return true;
}

/*** MANIPULASI SQL ***/

public function quote($query, $value, $key = 'col')
{
$ph = ':'.$key;
$query = str_replace('?', $ph, $query);
$this->bind[$key] = $value;

return $query;
}

public function query($sql, $bind = array())
{
if($sql instanceof Db_Select){
if(empty($bind))
$bind = $sql->getBind();

$sql = $sql->getSql();
}
else {
if(empty($bind))
$bind = $this->bind;
}

if(!is_array($bind))
$bind = array($bind);

$stmt = $this->_db->prepare($sql);
$stmt->execute($bind);
@$stmt->setFetchMode($this->_fetchMode);

return $stmt;
}

protected function _insert($table, $bind)
{
$vals = array();
foreach ($bind as $k => $v) {
$vals[] = ':' . $k;
}
$query = sprintf('INSERT INTO %s (%s) VALUES (%s)',
$table,
implode(',', array_keys($bind)),
implode(', ', $vals)
);

$stmt = $this->query($query, $bind);
$result = $stmt->rowCount();
return $result;
}

protected function _update($table, $data, $where)
{
$vals = array();
foreach ($data as $k => $v) {
$vals[] = $k . ' = :' . $k;
}

$this->bind = $data;

if(is_array($where))
$where = implode(' AND ', $where);

$query = sprintf('UPDATE %s SET %s WHERE %s',
$table,
implode(',', $vals),
$where
);

$stmt = $this->query($query);
$result = $stmt->rowCount();
return $result;
}

protected function _delete($table, $where)
{
if(is_array($where))
$where = implode(' AND ', $where);

$query = sprintf('DELETE FROM %s WHERE %s',
$table, $where
);

$stmt = $this->query($query);
$result = $stmt->rowCount();
return $result;
}

/*** SELECT QUERY ***/

public function select()
{
return new Db_Select($this);
}

public function fetchAll($query, $bind = array(), $fetchMode = null)
{
if ($fetchMode === null)
$fetchMode = $this->_fetchMode;

$stmt = $this->query($query, $bind);
return $stmt->fetchAll($fetchMode);
}

public function fetchAssoc($query, $bind = array())
{
$stmt = $this->query($query, $bind);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

public function fetchObj($query, $bind = array())
{
$stmt = $this->query($query, $bind);
return $stmt->fetchAll(PDO::FETCH_OBJ);
}

public function fetchPairs($sql, $bind = array())
{
$stmt = $this->query($sql, $bind);
return $stmt->fetch(PDO::FETCH_NUM);
}

public static function BuildMultiple($class, $data)
{
$ret = array();

if (!class_exists($class))
throw new Exception('Undefined class specified: ' . $class);

$testObj = new $class();

if (!$testObj instanceof DatabaseObject)
throw new Exception('Class does not extend from DatabaseObject');

foreach ($data as $row) {
$obj = new $class();
$obj->_init($row);

$ret[$obj->getId()] = $obj;
}

return $ret;
}
}
?>


Db_Select.php

<?php
class Db_Select
{
protected $_adapter;

const FROM = 'FROM';
const COLUMNS = 'COLUMNS';
const JOIN = 'JOIN';
const USING = 'USING';
const WHERE = 'WHERE';
const GROUP = 'GROUP';
const ORDER = 'ORDER';
const LIMIT_COUNT = 'LIMITCOUNT';
const LIMIT_OFFSET = 'LIMITOFFSET';

const INNER_JOIN = 'INNER JOIN';
const LEFT_JOIN = 'LEFT JOIN';
const RIGHT_JOIN = 'RIGHT JOIN';
const FULL_JOIN = 'FULL JOIN';
const NATURAL_JOIN = 'NATURAL JOIN';

const SQL_AND = 'AND';
const SQL_AS = 'AS';
const SQL_OR = 'OR';
const SQL_ON = 'ON';
const SQL_ASC = 'ASC';
const SQL_DESC = 'DESC';

protected $_parts = array();

protected static $_partsInit = array(
self::FROM => array(),
self::COLUMNS => array(),
self::WHERE => array(),
self::JOIN => array(),
self::GROUP => array()
);

public $_bind = array();

private $index = 1;

public function __construct(DatabaseObject $adapter)
{
$this->_adapter = $adapter;
$this->_parts = self::$_partsInit;
}

public function from($name = array(), $columns = array())
{
$this->_join(self::FROM, $name, $columns, null);
}

public function join($name, $columns = array(), $using)
{
$this->_join(self::INNER_JOIN, $name, $columns, sprintf('%s (%s)', self::USING, $using));
}

public function joinLeft($name, $columns = array(), $using)
{
$this->_join(self::LEFT_JOIN, $name, $columns, sprintf('%s (%s)', self::USING, $using));
}

public function joinRight($name, $columns = array(), $using)
{
$this->_join(self::RIGHT_JOIN, $name, $columns, sprintf('%s (%s)', self::USING, $using));
}

public function joinFull($name, $columns = array(), $using)
{
$this->_join(self::FULL_JOIN, $name, $columns, sprintf('%s (%s)', self::USING, $using));
}

public function joinNatural($name, $columns = array(), $using)
{
$this->_join(self::NATURAL_JOIN, $name, $columns, sprintf('%s (%s)', self::USING, $using));
}

protected function _join($type, $name, $columns, $cond)
{
if(is_array($name)){
foreach($name as $alias => $table){
$using = array($type, $table, $alias, $cond);
}

$this->_parts[self::JOIN][] = implode(' ', $using);
}
else
$this->_parts[self::JOIN][] = $type . ' ' . $this->_adapter->getTable();

if($columns)
$this->_parts[self::COLUMNS][] = implode(', ', $columns);
}

public function where($cond, $value = null)
{
$v = (is_array($value)) ? implode(',', $value) : $value;
$this->_parts[self::WHERE][] = $this->_where($cond, $v, true);
}

public function orWhere($cond, $value = null)
{
$v = (is_array($value)) ? implode(',', $value) : $value;
$this->_parts[self::WHERE][] = $this->_where($cond, $v, false);
}

protected function _where($condition, $value = null, $bool)
{
if($value !== null){
$condition = str_replace('?', $value, $condition);
}

$cond = "";
if ($this->_parts[self::WHERE]) {
if ($bool === true) {
$cond = self::SQL_AND . ' ';
} else {
$cond = self::SQL_OR . ' ';
}
}

return $cond . "$condition";
}

public function quote($quote, $value)
{
$quote = str_replace('?', ':col'.$this->index, $quote);
$this->_bind['col'.$this->index] = $value;
$this->index++;

return $quote;
}

public function group($group)
{
$this->_parts[self::GROUP] = $group;
return $this;
}

public function order($order, $type = null)
{
$type = (empty($type)) ? self::SQL_ASC : $type;

$this->_parts[self::ORDER] = $order . ' ' . $type;
return $this;
}

public function limit($count = null, $offset = null)
{
$this->_parts[self::LIMIT_COUNT] = (int) $count;
$this->_parts[self::LIMIT_OFFSET] = (int) $offset;
return $this;
}

public function getBind()
{
return $this->_bind;
}

public function getSQL()
{
if($this->_parts[self::COLUMNS]){
$query = sprintf('SELECT %s %s', join(', ', $this->_parts[self::COLUMNS]), join(' ', $this->_parts[self::JOIN]));
}
else{
$query = sprintf('SELECT * %s', join(' ', $this->_parts[self::JOIN]));
}

if($this->_parts[self::WHERE]){
$query .= sprintf(' WHERE %s', join(' ', $this->_parts[self::WHERE]));
}

if(!empty($this->_parts[self::GROUP])){
$query .= sprintf(' GROUP BY %s', $this->_parts[self::GROUP]);
}

if(!empty($this->_parts[self::ORDER])){
$query .= sprintf(' ORDER BY %s', $this->_parts[self::ORDER]);
}

if (!empty($this->_parts[self::LIMIT_OFFSET]) || !empty($this->_parts[self::LIMIT_COUNT])) {
$count = 0;
$offset = 0;
$offset = (int) ($this->_parts[self::LIMIT_OFFSET]) ? $this->_parts[self::LIMIT_OFFSET] : $offset;
$count = (int) ($this->_parts[self::LIMIT_COUNT]) ? $this->_parts[self::LIMIT_COUNT] : $count;
$query .= sprintf(' LIMIT %s, %s', $count, $offset);
}

return $query;
}
}
?>
Diubah oleh meong_garong 06-11-2013 07:29
0
1.2K
4
GuestAvatar border
Guest
Tulis komentar menarik atau mention replykgpt untuk ngobrol seru
Urutan
Terbaru
Terlama
GuestAvatar border
Guest
Tulis komentar menarik atau mention replykgpt untuk ngobrol seru
Komunitas Pilihan